1

我是设计模式的新手。
我想创建一个类的实例,比如 ClassA,并将它的一些字段设置为从配置文件中读取的值。
如果我将类的代码与使用值管理文件的代码区分开来,那么 ClassA 就变成了一个纯粹的“业务逻辑”类。

 class ClassA {
    boolean config1;
    String originDB;
    String destDB;
    //other fields not initialized at the construction time
  }

  class ClassAFactory {
    boolean config1;
    String originDB;
    String destDB;        

    public ClassAFactory {
      //constructor of the class factory
      //load config values from file
    }

    public ClassA newInstance() {
     //create a new instance of ClassA and config fields config1, originDB, destDB
    }

  }

我会说这是一种构建器模式,因为构建器似乎“不仅负责实例化”,还负责初始化。
但除此之外,builder 似乎专注于逐步打破创建过程,而在我的情况下,我只有一个(但复合的)步骤。

可以被认为是构建器模式吗?还是有什么不同?

4

2 回答 2

3

没有步骤- 没有Builder

    ClassA a = ClassABuilder
            .config(config1)
            .originDB(originDB)
            .destDB(destDB)
            .build();
    // above reads a Builder to me and hopefully to any reader
    //   note above allows to swap, add, remove particular steps


    ClassA a = ClassAFactory.newInstance();
    // above reads Factory to me and hopefully to any reader
    //   note for reader, it's a one-step thing
于 2011-09-13T21:08:39.203 回答
1

看起来更像是工厂模式而不是生成器。这是因为只有一种方法可以完成所有工作。通常,构建器将具有一组 setter 样式的方法,这些方法将允许自定义正在构建的对象。

于 2011-09-13T20:13:30.517 回答