Enum工厂式的方法

Ste*_*eve 11 java enums factory

在我的应用程序中,可以生成几个不同的报告(CSV,HTML等).

我没有创建传统的工厂式方法模式,而是计划在枚举常量体中添加一个方法,该方法将创建并返回相应的报表对象.

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

 public abstract Report create();
}
Run Code Online (Sandbox Code Playgroud)

使用指定的ReportType枚举常量,我可以通过执行如下语句轻松创建新报表:

ReportType.CSV.create()
Run Code Online (Sandbox Code Playgroud)

我希望得到其他人对使用这种方法的看法.你觉得这怎么样?你更喜欢其他任何方法,如果有的话,为什么?

谢谢

Luc*_*ira 5

我认为两种方法都可以,但是如果您不想知道要生成哪种报告,那么我认为枚举方法是最好的。像这样:

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

    public ReportType getMyPreferedReportType(){
        return this.myPreferedReportType;
    }
    //other getters & setters...
}
Run Code Online (Sandbox Code Playgroud)

假设您将Person实例持久保存在数据库中,以后再检索它-如果使用多态性,则无需任何开关。您唯一需要做的就是调用create()方法。喜欢:

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

因此,如果您依赖多态性,则无需要求工厂明确获得CVS / HTML / PDF,而将工作交给Enum本身即可。但是当然,在某些情况下,您可能需要使用一种或另一种,尽管我倾向于定期使用枚举方法。