Enum工厂式的方法

时间:2010-01-29 16:39:27

标签: 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();
}

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

ReportType.CSV.create()

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

谢谢

4 个答案:

答案 0 :(得分:5)

我认为这两种方法都可以,但如果你不想知道你正在生成哪种报告,那么我相信enum方法是最好的。像这样:

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

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

让你在数据库中持久化Person实例并在以后检索它 - 如果你使用polimorphism,你就不需要任何交换机了。你唯一需要做的就是 调用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();

因此,如果您依赖于polimorphism,您将无需要求工厂明确地为您提供CVS / HTML / PDF,将该工作留给Enum本身。但是,当然,有些情况下您可能需要使用其中一种,但我倾向于定期使用枚举方法。

答案 1 :(得分:3)

使用枚举作为报告创建的例子有什么好处?如果您有工厂方法,那么您将创建一个CSVReport实例(如下所示):

Report csvReport = ReportFactory.createCSVReport();

Report csvReport = ReportFactory.createCSVReport(); 我认为这比enum更能传达意图。据我所知,Enumerations代表一组固定的常量,并将其用作实例创建的工厂(虽然有效)似乎误用了Enumeration的意图。

答案 2 :(得分:2)

查看Enum with Visitor Pattern。使用这种方法,您将能够动态地向枚举添加功能,而不必污染枚举本身。

答案 3 :(得分:1)

Joshua Bloch(公认的Java专家)实际上在第17页的Effective Java 2nd Edition一书中推荐了这种方法:使用私有强制执行单例属性 构造函数或枚举类型。

相关问题