参考:
https://github.com/me115/design_patterns
https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/simple_factory.html
工厂模式分为三种
一:简单工厂模式(Simple Factory Pattern)
包括三个角色:
Factory :工厂角色
Product:抽象产品角色
ConcreteProduct:具体产品角色
具体产品角色实现抽象产品橘色,工厂类则负责produce
示例代码:
main
public class Test {
public static void main(String args) {
Factory.produce("A").doSomeThing();
}
}
interface Base{
void doSomeThing();
}
class A implements Base {
public void doSomeThing(){}
}
class B implements Base {
public void doSomeThing(){}
}
factory
public class Factory {
public static Base produce(String type) {
if ("A".equals(type)) {
return new A();
}
else if("B".equals(type)) {
return new B();
}
else {
return null;
}
}
}
要点:某个类只能有一个实例,提供一个全局的访问点 (或者是静态方法也行)
二 工厂方法模式(Factory Method Pattern)
简单工厂模式如果要新增一种产品种类的话,需要修改工厂,这违悖了开闭原则,
而工厂方法模式则抽象出来工厂类,将工厂类的具体实现交给子类来实现,这样如果新增产品的话,只要
增加一个工厂即可
角色:
Product:抽象产品
ConcreteProduct:具体产品
Factory:抽象工厂
ConcreteFactory:具体工厂
代码
产品:
class A implements Base {
public void doSomeThing(){}
}
class B implements Base {
public void doSomeThing(){}
}
interface Base{
void doSomeThing();
}
工厂:
public class FactoryA implements Factory{
public Base produce(String type) {
if ("A".equals(type)) {
return new A();
}
else {
return null;
}
}
}
public class FactoryB implements Factory{
public Base produce(String type) {
if("B".equals(type)) {
return new B();
}
else {
return null;
}
}
}
public interface Factory {
Base produce(String type);
}
main
public class Test {
public static void main(String args) {
Factory a = new FactoryA();
a.produce("A").doSomeThing();
}
}