繁体   English   中英

创建同一类的不同实例,采用哪种设计模式?

[英]Create different instances of the same class, which design pattern?

我有一个自定义对象ExportType

public class ExportType{

    protected String name;      
    protected FetchingStrategy fetchStg;
    protected ExportStrategy exportStg;

    public ExportType(String name, FetchingStrategy fetch, ExportStrategy export) {
            this.name = name;
        this.fetchStg = fetch;
        this.exportStg = export;
    }

    // ...
}

在我的应用程序中,我必须创建一个具有不同FetchingStrategyExportStrategy的Export类型的列表。 通过实现新的FetchingStrategyExportStrategy ,可以在将来创建新的Export类型,因此我希望将应用程序设计得尽可能灵活。

我是否应该申请一种设计模式才能获得所需的东西? 为每个ExportType特定实例创建一个不同的TypeFactory是正确的方法吗?

UPDATE

我尝试总结一下我的问题:我正在开发一个Web应用程序,用于从db导出数据。 我有几种从DB( ExportType )提取数据的方法,这些类型是通过FetchingStrategyExportStrategy不同组合获得的。 现在,我需要创建这些“组合”的列表,以便在必要时调用它们。 我可以创建如下常量:

public static final ExportType TYPE_1 = new ExportType(..., ...);

但我想以某种方式实现它,以便将来可以添加新的组合/类型。

最好的设计模式是使用返回所有接口的工厂。 然后,您可以抽象出所有实现,从而可以灵活地扩展和更改系统。

Spring依赖注入是一个很好的解决方案

您最大的问题可能是在数据库级别,这很难抽象

您可以使用AbstractFactory: http : //en.wikipedia.org/wiki/Abstract_factory_pattern

有关您计划使用这些方式的更多详细信息可能会有所帮助。

为了尽可能灵活,请不要使用具体的类。 使用界面。

我建议Spring IoC在ExportType中注入FetchingStrategy和ExportStrategy的不同实现。

public class SomeExportType implements IExportType{

    protected String name;
    @Autowired(@Qualifier="SomeFetchingStrategy")      
    protected IFetchingStrategy fetchStg;
    @Autowired(@Qualifier="SomeExportStrategy")      
    protected IExportStrategy exportStg;



    // ...
}

public interface IExportType {
     public void doSomething();  //
}

public interface IFetchingStrategy {
   public void fetch();
}

public class SomeFetchingStrategy implements IFetchingStrategy {

    public void fetch() {
        //implement this strategy
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM