创建型-抽象工厂模式

概念

Abstract Factory Pattern:提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类。

img

与工厂模式的区别

抽象工厂模式中:生产产品的工厂是抽象的。比如,可口可乐生产可乐的同时,还要生产可口可乐的瓶子、箱子,百事可乐也一样,所以要把工厂抽象出来,专门生产同一主题的不同商品

使用

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// 可乐抽象类
class Cola {
//
}
// 瓶子抽象类
class Bottle {
//
}
// 箱子抽象类
class Box {
//
}
// 工厂抽象类
class Factory {
creatCola() {
return new Cola();
}
}


// 可口可乐主题工厂
class CocaColaFactory extends Factory {
creatCola() {
return new CocaCola();
}
creatBottle() {
return new CocaColaBottle();
}
creatBox() {
return new CocaColaBox();
}
}
// 可口可乐产品类
class CocaCola extends Cola {
product (type) {
return `生产可口可乐`
}
}
// 可口可乐瓶子类
class CocaColaBottle extends Cola {
product (type) {
return `生产可口可乐瓶子`
}
}
// 可口可乐箱子类
class CocaColaBox extends Cola {
product (type) {
return `生产可口可乐箱子`
}
}

// 百世可乐主题工厂
class PesiColaFactory extends Factory {
creatCola() {
return new PesiCola();
}
creatBottle() {
return new PesiColaBottle();
}
creatBox() {
return new PesiColaBox();
}
}
// 百世可乐产品类
class PesiCola extends Cola {
product (type) {
return `生产百世可乐`
}
}
// 百世可乐瓶子类
class PesiColaBottle extends Cola {
product (type) {
return `生产百世可乐瓶子`
}
}
// 百世可乐箱子类
class PesiColaBox extends Cola {
product (type) {
return `生产百世可乐箱子`
}
}

// 生产可口可乐
let cocaCola = new CocaColaFactory().creatCola();
let cocaColaBottle = new CocaColaFactory().creatBottle();
let cocaColaBox = new CocaColaFactory().creatBox();
// 生产百世可乐
let pesiCola = new PesiColaFactory().creatCola();
let pesiColaBottle = new PesiColaFactory().creatBottle();
let pesiColaBox = new PesiColaFactory().creatBox();

优点

  • 具有工厂模式的优点,还可以在类中对产品族进行约束,如果产品比较多,更应该使用抽象工厂模式而不是工厂模式(适合只要一个产品)

缺点

  • 扩展性比较费力,尤其是系统比较庞大的时候,产品族需要增加一个新的产品,就要在工厂类进行修改