白筱汐

想都是问题,做都是答案

0%

JavaScript设计模式——抽象工厂模式

抽象工厂模式

抽象工厂模式提供一个创建一系列相关或相互依赖对象的家族,而无须指定它们具体的类。 抽象工厂模式主要包含4种角色:抽象工厂、具体工厂、抽象产品、具体产品。 抽象类提供接口的定义,具体类需要实现抽象接口。

typescript 代码

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
// 抽象产品
interface Button {
paint(): void;
}

interface Label {
paint(): void;
}

// 具体产品
class WinButton implements Button {
paint() {
console.log("WinButton is painted.");
}
}

class WinLabel implements Label {
paint() {
console.log("WinLabel is painted.");
}
}

class MacButton implements Button {
paint() {
console.log("MacButton is painted.");
}
}

class MacLabel implements Label {
paint() {
console.log("MacLabel is painted.");
}
}

// 抽象工厂
interface AbstractFactory {
createButton(): Button;
createLabel(): Label;
}

// 具体工厂
class WinFactory implements AbstractFactory {
createLabel(): Label {
return new WinLabel();
}
createButton(): Button {
return new WinButton();
}
}

class MacFactory implements AbstractFactory {
createLabel(): Label {
return new MacLabel();
}
createButton(): Button {
return new MacButton();
}
}

// 客户端
class App {
private factory: AbstractFactory;

constructor(factory: AbstractFactory) {
this.factory = factory;
}

createUI() {
const button: Button = this.factory.createButton();
const label: Label = this.factory.createLabel();
button.paint();
label.paint();
}
}

// 使用抽象工厂创建不同的 UI
const app1: App = new App(new WinFactory());
const app2: App = new App(new MacFactory());

app1.createUI();
app2.createUI();