代码之家  ›  专栏  ›  技术社区  ›  Rui

当工厂需要创建具有多个公共参数的对象时,如何解决这个难题?

  •  2
  • Rui  · 技术社区  · 7 年前

    PageRenderer

    • ImagePageRenderer
    • TextPageRenderer
    • VideoPageRenderer .

    所以为了得到 页面渲染器 工厂法 是合适的。这个 concreate 工厂看起来是这样的:

    public class PageRendererFactory extends AbstractFactory {
      PageRenderer createPageRenderer(Type type) {
        //implementation
      }
    }//Code AbstractFactory is skipped here
    

    页面渲染器 包含子类要使用的几个实例变量:

    public abstract class PageRenderer {
      protected A a;
      protected B b;
      protected C c;
      protected D d;
      Protected E e;
      //there might be even more instance variables
    }
    

    以及 页面渲染器 共享这些实例变量。

    根据上述条件,我将更改 PageRendererFactory 因此,它包含所提到的 实例变量 :

    public class PageRendererFactory extends AbstractFactory {
      private A a;
      private B b;
      private C c;
      private D d;
      Private E e;
      //there might be even more instance variables here
      PageRenderer createPageRenderer(Type type) {
        //use the instance variables to instantiate the subclass of PageRenderer according to the Type
      }
    }//Code AbstractFactory is skipped here
    

    问:在这种情况下,我可能需要在这方面的二传手 页面渲染器工厂 ,但这家工厂似乎和 构建器模式 ! 那么这是一个好的解决方案吗?或者有没有更好的替代方案?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Bor Laze    7 年前

    您使用工厂的决定是正确的。

    这家工厂将如何创建并不重要。

    直拨

    Factory factory = new Factory();
    

    通过直接调用setter

    Factory factory = new Factory();
    factory.setA(a);
    ...
    factory.setE(e);
    

    Factory factory = new Factory(a, b, c, d, e);
    

    Factory factory = new Factory.Builder()
        .withA(a)
        ...
        .withE(e)
        .build();