工厂方法模式

发布于 2019-01-24 | 更新于 2021-12-05

1、简单工厂方法模式

image-20191130180641009

如上图,运输工具包含了飞机和轮船,统一由运输工厂创建。

运输工具接口:

1
2
3
public interface Transportation {
void transport();
}

飞机:

1
2
3
4
5
6
7
public class AirPlaneTransport implements Transportation{

@Override
public void transport() {
System.out.println("Transport by airplane...");
}
}

轮船:

1
2
3
4
5
6
7
public class SteamerTransport implements Transportation {

@Override
public void transport() {
System.out.println("transport by steamer...");
}
}

运输工具工厂:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class TransportFactory {

public static Transportation createTransport(int type) {
Transportation result = null;
switch (type) {
case TransportConstants.TYPE_AIRPLANE:
result = new AirPlaneTransport();
break;
case TransportConstants.TYPE_STEAMER:
result = new SteamerTransport();
break;
}
return result;
}

public static void main(String[] args) {
Transportation transportation = TransportFactory.createTransport(TransportConstants.TYPE_AIRPLANE);
transportation.transport();
}

}

1.1、优点

  • 达到了对象创建和使用分离的目的;
  • 客户端通过传入特定类型参数直接通过工厂类创建产品,无需知道具体类名;
  • 如果需要新增具体产品,无需修改客户端调用代码,提供系统灵活性。

1.2、缺点

  • 工厂中需要根据特性类型来创建产品,职责过重;
  • 添加新的具体产品,需要修改工厂方法,违反了开闭原则;
  • 简单工厂是静态方法,无法继承扩展,不能形成基于工厂的继承体系。

2、工厂方法模式

3、抽象工厂模式

References

工厂方法模式

【设计模式】简单工厂、工厂方法与抽象工厂的区别

本文作者: arthinking

本文链接: https://www.itzhai.com/articles/factory-method.html

版权声明: 版权归作者所有,未经许可不得转载,侵权必究!联系作者请加公众号。

×
IT宅

关注公众号及时获取网站内容更新。