-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactory.cpp
More file actions
71 lines (59 loc) · 1.35 KB
/
factory.cpp
File metadata and controls
71 lines (59 loc) · 1.35 KB
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
#include <iostream>
using namespace std;
// 产品接口
class IProduct {
public:
virtual ~IProduct() = default;
virtual void func() = 0;
};
// 工厂接口
class IFactory {
public:
virtual ~IFactory() = default;
virtual IProduct* create() = 0;
};
// 产品 1
class Product1 : public IProduct {
public:
void func() override {
cout << "Product1" << endl;
}
};
// 产品 1 工厂
class FactoryProduct1 : public IFactory {
public:
IProduct* create() override {
return new Product1();
}
};
// 产品 2
class Product2 : public IProduct {
public:
void func() override {
cout << "Product2" << endl;
}
};
// 产品 2 工厂
class FactoryProduct2 : public IFactory {
public:
IProduct* create() override {
return new Product2();
}
};
// test 模块摆脱 new Product1()、new Product2() 固定类型依赖
// 直接传进来指定产品,不也可摆脱固定类型依赖,为什么还要工厂?
// test 模块要的不是某个产品,要的是创建产品的方法
void test(IFactory* factory) {
IProduct* pro1 = factory->create();
pro1->func();
IProduct* pro2 = factory->create();
pro2->func();
}
int main() {
IFactory* factory1 = new FactoryProduct1();
test(factory1);
cout << endl;
IFactory* factory2 = new FactoryProduct2();
test(factory2);
return 0;
}