Enum factory-style method

Steve picture Steve · Jan 29, 2010 · Viewed 9.3k times · Source

In my application, several different reports can be generated (CSV, HTML, etc).

Instead of creating a traditional factory-style method pattern, I was planning on adding a method to the body of enum constants that would create and return the appropriate report object.

public enum ReportType {
 CSV {
  @Override
  public Report create() {
   return new CSVReport();
  }
 },
 HTML {
  @Override
  public Report create() {
   return new HTMLReport();
  }
 };

 public abstract Report create();
}

With a specified ReportType enum constant, I could then easily create a new report by executing a statement like the following:

ReportType.CSV.create()

I wanted to get the opinion of others on using this approach. What do you think of this? Would you prefer any other approach, and if so, why?

Thanks

Answer

Lucas de Oliveira picture Lucas de Oliveira · Feb 10, 2010

I think both approaches are ok, but if you don't want to know which kind of report you're generating then I believe that the enum approach is the best. Like so:

public class Person { 
    private String name;
    private ReportType myPreferedReportType;

    public ReportType getMyPreferedReportType(){
        return this.myPreferedReportType;
    }
    //other getters & setters...
}

supose you persist a Person instance on a database and retrieve it later on - if you use polimorphism you won't need any switch wathsoever. The only thing you'll need to do is to call the create() method. Like:

Person person = null; 
//... retrieve the person instance from database and generate a 
//report with his/her prefered report type...
Report report = person.getReportType.create();

So if you rely on polimorphism you won't need to ask a factory to get you the CVS/HTML/PDF explicitly, leaving that work to the Enum itself. But of course, there are situations that you may need to use one or another, although I tend to use the enum approach regularly.