简单工厂模式(非 GoF 中模式)-02

发布时间 2023-06-13 11:26:36作者: CSloe

概述

简单工厂模式(simple factory pattern) 又称静态工厂方法(static factory method) 模式。这个模式由一个工厂类、一个抽象产品类以及继承自这个抽象产品类的多个具体子类组成。工厂类中用于创建产品类的方法根据传入参数的不同返回不同类型的具体产品子类。

优点:对象创建和使用分离,不需要知道对象创建过程;提高系统灵活性。
缺点:增加了类的数量,在一定程度上变得复杂;扩展需要修改工厂类。

interface Parent {
  void m();
}

class SubOne implements Parent {
  void m() {
    //
  }
}

class SubTwo implements Parent {
  void m() {
    //
  }
}

class ParentFactory {
  public static Parent getParent(String s) {
    if (s == "subone") {
      return new SubOne();
    } else if (s == "subtwo") {
      return new SubTwo();
    } else {
      return null;
    }
  }
}

public class Test {
  public static void main(String[] args) {
    Parent p = ParentFactory.getParent("subone");
    p.m();
  }
}


图示:

image

参考

[1]. 刘伟, 设计模式. 2011.