抽象工厂模式

模式意图

通常,我们一个工厂可以生产一个产品。现在我们有个需求需要将不同的产品组合在一起在一个工厂中生产。抽象工厂方法又称为Kit,工具箱,创造一组相关的对象。

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

抽象工厂方法可以创造一个产品族,例如一个王国需要有国王King、城堡Castle、军队Army,我们想使用一个工厂可以把这一系列有关联的产品全部创造出来,同时客户端在使用的时候不需要指定具体的产品实现。抽象工厂模式工厂方法模式最大的区别在于,工厂方法模式针对的是一个产品等级结构,而抽象工厂模式则需要面对多个产品等级结构
Wikipedia:

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.

抽象工厂方法的使用场景

在以下情况下考虑使用抽象工厂方法:

  1. 当一个系统应该独立于其产品是如何创建、组合和表示的。
  2. 当一个系统应该配置多个产品系列之一。
  3. 当需要在运行时来确定使用的是哪个产品系列

抽象工厂方法强调的是将一系列的对象进行封装,并且将实现和定义分离开来,在运行时来决定使用哪个工厂。

具体实例

每个王国都由一系列的对象组成,KingCastle 以及ArmyKingdomFactory 是一个王国的工厂接口,它负责创造一个王国,也就是一个抽象工厂。针对每个王国都有一个工厂的具体实现。如图所示。
抽象工厂方法类图
具体代码如下:
KingdomFactory 接口,王国的工厂接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
*
* KingdomFactory factory interface.
*
*/
public interface KingdomFactory {

Castle createCastle();

King createKing();

Army createArmy();

}

KingdomFactory 的两个实现类ElfKingdomFactoryOrcKingdomFactory :

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
30
31
32
33
34
35
36
37
38
39
40
/**
*
* ElfKingdomFactory concrete factory.
*
*/
public class ElfKingdomFactory implements KingdomFactory {

public Castle createCastle() {
return new ElfCastle();
}

public King createKing() {
return new ElfKing();
}

public Army createArmy() {
return new ElfArmy();
}

}

/**
*
* OrcKingdomFactory concrete factory.
*
*/
public class OrcKingdomFactory implements KingdomFactory {

public Castle createCastle() {
return new OrcCastle();
}

public King createKing() {
return new OrcKing();
}

public Army createArmy() {
return new OrcArmy();
}
}

客户端在使用时:

1
2
3
4
5
6
7
8
9
10
/**
* Creates kingdom
*/
public void createKingdom(final KingdomFactory factory) {
setKing(factory.createKing());
setCastle(factory.createCastle());
setArmy(factory.createArmy());
}
//将ElfKindomFactory或者OrcKingdomFactory作为参数传递进去就能够
//创造一个王国了 - -

运行结果:

1
2
3
4
5
6
7
8
16:12:37.079 [main] INFO com.iluwatar.abstractfactory.App - Elf Kingdom
16:12:37.090 [main] INFO com.iluwatar.abstractfactory.App - This is the Elven Army!
16:12:37.090 [main] INFO com.iluwatar.abstractfactory.App - This is the Elven castle!
16:12:37.090 [main] INFO com.iluwatar.abstractfactory.App - This is the Elven king!
16:12:37.090 [main] INFO com.iluwatar.abstractfactory.App - Orc Kingdom
16:12:37.110 [main] INFO com.iluwatar.abstractfactory.App - This is the Orc Army!
16:12:37.110 [main] INFO com.iluwatar.abstractfactory.App - This is the Orc castle!
16:12:37.110 [main] INFO com.iluwatar.abstractfactory.App - This is the Orc king!