工厂模式

不直接new

简单工厂


场景

工厂统一管理创建,使用方只告知所需类型,由工厂负责创建

代码


Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
interface Product{
void work();
}

class ProductA implements Product{
public void work(){
//logic
}
}

class ProductB implements Product{
public void work(){
//logic
}
}

class Factory{
public Product produce(String type) {
if(type == null){
return null;
}
if(type.equals("A")){
return new ProductA();
}else if(type.equals("B")){
return new ProductB();
}
}
}

为了避免过多的if-else,还可以考虑用反射机制
fqcn可以使用注解/配置文件,避免手动传入

Sample
1
2
3
4
5
6
7
8
9
class Factory{
public Product produce(String fqcn) throws Exception {
if(type == null){
return null;
}
Class clazz = Class.forName(fqcn);
return (Product)clazz.newInstance();
}
}

优缺点


  • 客户端无需知道创建细节
  • 工厂统一创建,代码逻辑集中
  • 工厂可以附加额外逻辑,比如单例,缓存等

应用


java.nio.charset.Charset的forName方法

抽象工厂


工厂也有体系,每个工厂生产一组产品套系
工厂也进行了一层抽象,实现了更高层接口,工厂的工厂

Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface Factory{
Product produce();
}

class FactorySeries1 implements Factory{
public Product produce(){
//logic
}
}

class FactorySeries2 implements Factory{
public Product produce(){
//logic
}
}

class AbstractFactory {
public Factory getFactory(String factoryName){
//return
}
}

应用

javax.xml.xpath.XPathFactory的newInstance方法
javax.xml.parsers.DocumentBuilderFactory的newInstance方法