设计模式之抽象工厂模式

我们定义了抽象产品A和B以及它们的具体实现类。然后,我们定义了抽象工厂和具体工厂1和2,每个具体工厂都实现了创建产品A和B的方法。在主函数中,我们使用具体工厂1和2创建了产品A和B。

跟简单工厂模式不一样的是,工厂也变成了多个工厂,即举个例子,肯德基和麦当劳都可以做不一样的炸鸡汉堡。

实现

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
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>

// 抽象产品A
class AbstractProductA {
public:
virtual void operationA() = 0;
};

// 具体产品A1
class ConcreteProductA1 : public AbstractProductA {
public:
void operationA() override {
std::cout << "ConcreteProductA1 operationA" << std::endl;
}
};

// 具体产品A2
class ConcreteProductA2 : public AbstractProductA {
public:
void operationA() override {
std::cout << "ConcreteProductA2 operationA" << std::endl;
}
};

// 抽象产品B
class AbstractProductB {
public:
virtual void operationB() = 0;
};

// 具体产品B1
class ConcreteProductB1 : public AbstractProductB {
public:
void operationB() override {
std::cout << "ConcreteProductB1 operationB" << std::endl;
}
};

// 具体产品B2
class ConcreteProductB2 : public AbstractProductB {
public:
void operationB() override {
std::cout << "ConcreteProductB2 operationB" << std::endl;
}
};

// 抽象工厂
class AbstractFactory {
public:
virtual AbstractProductA* createProductA() = 0;
virtual AbstractProductB* createProductB() = 0;
};

// 具体工厂1
class ConcreteFactory1 : public AbstractFactory {
public:
AbstractProductA* createProductA() override {
return new ConcreteProductA1();
}

AbstractProductB* createProductB() override {
return new ConcreteProductB1();
}
};

// 具体工厂2
class ConcreteFactory2 : public AbstractFactory {
public:
AbstractProductA* createProductA() override {
return new ConcreteProductA2();
}

AbstractProductB* createProductB() override {
return new ConcreteProductB2();
}
};

int main() {
// 使用具体工厂1创建产品
AbstractFactory* factory1 = new ConcreteFactory1();
AbstractProductA* productA1 = factory1->createProductA();
AbstractProductB* productB1 = factory1->createProductB();
productA1->operationA();
productB1->operationB();

// 使用具体工厂2创建产品
AbstractFactory* factory2 = new ConcreteFactory2();
AbstractProductA* productA2 = factory2->createProductA();
AbstractProductB* productB2 = factory2->createProductB();
productA2->operationA();
productB2->operationB();

delete factory1;
delete productA1;
delete productB1;

delete factory2;
delete productA2;
delete productB2;

return 0;
}