工厂方法模式使用的频率非常高,在我们日常的开发中总能见到它的身影。

定义:

定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

通用类图:

设计模式之创建类模式——工厂方法模式

通用源码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 抽象产品类
* @author Administrator
*
*/
publicabstractclassProduct {
// 产品类的公共方法
publicvoidmethod1() {
// 业务处理逻辑
}
// 抽象方法
publicabstractvoidmethod2();
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 具体产品类1
* @author Administrator
*
*/
publicclassConcreteProduct1extendsProduct {
@Override
publicvoidmethod2() {
// 业务逻辑处理
}
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 具体产品类2
* @author Administrator
*
*/
publicclassConcreteProduct2extendsProduct {
@Override
publicvoidmethod2() {
// 业务逻辑处理
}
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 抽象工厂类
* @author Administrator
*
*/
publicabstractclassCreator {
/**
* 创建一个产品对象,其输入参数类型可以自行设置
* 通常为String、Enum、Class等,当然也可以为空
* @param <T>
* @param c
* @return
*/
publicabstract<TextendsProduct> T createProduct(Class<T> c);
}

?
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
/**
* 具体工厂类
*
* @author Administrator
*
*/
publicclassConcreteCreatorextendsCreator {
@Override
public<TextendsProduct> T createProduct(Class<T> c) {
Product product = null;
try{
product = (Product) Class.forName(c.getName()).newInstance();
}catch(InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return(T) product;
}
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 场景类
*
* @author Administrator
*
*/
publicclassClient {
/**
* @param args
*/
publicstaticvoidmain(String[] args) {
Creator creator = newConcreteCreator();
Product product = creator.createProduct(ConcreteProduct1.class);
/*
* 继续业务处理
*/
product.method1();
}
}

工厂方法模式的优点:

  1. 良好的封装性,代码结构清晰。一个对象创建是有条件约束的,如一个调用者需要一个具体的产品对象,只要知道这个产品的类名(或约束字符串)就可以了,不用知道创建对象的艰辛过程,降低模块间的耦合。
  2. 工厂方法模式的扩展性非常优秀。在增加产品类的情况下,只要适当地修改具体的工厂类或扩展一个工厂类,就可以完成“拥抱变化”。
  3. 屏蔽产品类。这一点非常重要,产品类的实现如何变化,调用者都不需要关系,它只需要关心产品的接口,只要接口保持不变,系统中的上层模块就不要发生变化。因为产品类的实例化工作是由工厂类负责的,一个产品对象具体由哪一个产品生成是由工厂类决定的。
  4. 工厂方法模式是典型的解耦框架。高层模块只需要知道产品的抽象类,其他的实现类都不用关心,符合迪米特法则,我不需要的就不要去交流;也符合依赖倒置原则,只依赖产品类的抽象;当然也符合里氏替换原则,使用产品子类替换父类也没问题。

工厂方法模式的使用场景:

  1. 工厂方法模式是new一个对象的替代品,所以在所有需要生成对象的地方都可以使用,到那时需要慎重考虑是否要增加一个工厂类进行管理,增加代码的复杂度。
  2. 需要灵活的、可扩展的框架时,可以考虑采用工厂方法模式。
  3. 工厂方法模式可以用在异构项目中。
  4. 可以使用在测试驱动开发的框架下。

工厂方法模式的扩展:

  • 缩小为简单工厂模式

简单工厂模式(Simple Factory Pattern),也叫做静态工厂模式。在实际项目中,采用该方法的案例还是比较多的,其缺点是工厂类的扩展比较困难,不符合开闭原则,但它仍然是一个非常实用的设计模式。

类图:

设计模式之创建类模式——工厂方法模式

通用代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 抽象产品类
* @author Administrator
*
*/
publicabstractclassProduct {
// 产品类的公共方法
publicvoidmethod1() {
// 业务处理逻辑
}
// 抽象方法
publicabstractvoidmethod2();
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 具体产品类1
* @author Administrator
*
*/
publicclassConcreteProduct1extendsProduct {
@Override
publicvoidmethod2() {
// 业务逻辑处理
}
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 具体产品类2
* @author Administrator
*
*/
publicclassConcreteProduct2extendsProduct {
@Override
publicvoidmethod2() {
// 业务逻辑处理
}
}

?
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
/**
* 简单工厂模式中的工厂类
* @author Administrator
*
*/
publicclassSimpleFactory {
publicstatic<TextendsProduct> T createProduct(Class<T> c) {
Product product = null;
try{
product = (Product)Class.forName(c.getName()).newInstance();
}catch(InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return(T) product;
}
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 场景类
*
* @author Administrator
*
*/
publicclassClient {
/**
* @param args
*/
publicstaticvoidmain(String[] args) {
Product product = SimpleFactory.createProduct(ConcreteProduct1.class);
/*
* 继续业务处理
*/
product.method1();
}
}

  • 升级为多个工厂类

多工厂模式中,每一个产品类都对应一个创建类,好处就是创建类的职责清晰,而且结构简单,但是给可扩展性和可维护性带来了一定的影响。为什么这么说呢?如果要扩展一个产品类,就需要建立一个相应的工厂类,这样就增加了扩展的难度。因为工厂类和产品类的数量相同,维护时需要考虑两个对象之间的关系。

当然,在复杂的应用中一般采用多工厂的方法,然后在增加一个协调类,避免调用者与各个子工厂交流,协调类的作用是封装子工厂类,对高层模块提供统一的访问接口。

类图:

设计模式之创建类模式——工厂方法模式

通用代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 抽象产品类
* @author Administrator
*
*/
publicabstractclassProduct {
// 产品类的公共方法
publicvoidmethod1() {
// 业务处理逻辑
}
// 抽象方法
publicabstractvoidmethod2();
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 具体产品类1
* @author Administrator
*
*/
publicclassConcreteProduct1extendsProduct {
@Override
publicvoidmethod2() {
// 业务逻辑处理
}
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 具体产品类2
* @author Administrator
*
*/
publicclassConcreteProduct2extendsProduct {
@Override
publicvoidmethod2() {
// 业务逻辑处理
}
}

?
1
2
3
4
5
6
7
8
9
10
/**
* 多工厂模式的抽象工厂类
*
* @author Administrator
*
*/
publicabstractclassAbstractProductFactory {
publicabstractProduct createProduct();
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 创建Product1的具体工厂类
* @author Administrator
*
*/
publicclassProduct1FactoryextendsAbstractProductFactory {
@Override
publicProduct createProduct() {
returnnewConcreteProduct1();
}
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 创建Product2的具体工厂类
* @author Administrator
*
*/
publicclassProduct2FactoryextendsAbstractProductFactory {
@Override
publicProduct createProduct() {
returnnewConcreteProduct2();
}
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 场景类
*
* @author Administrator
*
*/
publicclassClient {
/**
* @param args
*/
publicstaticvoidmain(String[] args) {
AbstractProductFactory productFactory = newProduct1Factory();
Product product = productFactory.createProduct();
/*
* 继续业务处理
*/
product.method1();
}
}

  • 替代单例模式

通过反射方式创建,获得类构造器,然后设计访问权限,生成一个对象,然后提供外部访问,保证内存中的对象唯一。

通过工厂方法模式创建了一个单例对象,在一个项目中可以产生一个单例构造器,所有需要产生单例的类都遵循一定的规则(构造方法是private),然后通过扩展该框架,只要输入一个类型就可以获得唯一的一个实例。

类图:

设计模式之创建类模式——工厂方法模式

通用代码:

?
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
29
/**
* 负责生成单例的工厂类
*
* @author Administrator
*
*/
publicclassSingletonFactory {
privatestaticSingleton singleton;
static{
try{
Class cl = Class.forName(Singleton.class.getName());
// 获得无参构造
Constructor constructor = cl.getDeclaredConstructor();
// 设置无参构造是可访问的
constructor.setAccessible(true);
// 产生一个实例对象
singleton = (Singleton) constructor.newInstance();
}catch(Exception e) {
// 异常处理
}
}
publicstaticSingleton getSingleton() {
returnsingleton;
}
}

  • 延迟初始化(Lazy initialization)

一个对象被消费完毕后,并不立即释放,工厂类保持其初始状态,等待再次被使用。延迟初始化是工厂方法模式的一个扩展应用。

类图:

设计模式之创建类模式——工厂方法模式

通用代码:

?
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
29
/**
* 延迟加载的工厂类
*
* @author Administrator
*
*/
publicclassLazyInitFactory {
privatestaticfinalMap<String, Product> prMap = newHashMap<String, Product>();
publicstaticsynchronizedProduct createProduct(String type) throwsException {
Product product = null;
// 如果Map中已经有这个对象
if(prMap.containsKey(type)) {
product = prMap.get(type);
}else{
if(type.equals("Product1")) {
product = newConcreteProduct1();
}else{
product = newConcreteProduct2();
}
// 同时把对象放到缓存容器中
prMap.put(type, product);
}
returnproduct;
}
}

延迟加载框架是可以扩展的,例如限制某一个产品类的最大实例化数量,可以通过判断Map中已有对象数量来实现。

延迟加载还可以用在对象初始化比较复杂的情况下,例如硬件访问,涉及多方面的交互,则可以通过延迟加载降低对象的产生和销毁带来的复杂性。

相关文章: