-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.cpp
81 lines (64 loc) · 1.69 KB
/
main.cpp
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
/*
* @FileName : factory_method/main.cpp
* @CreateAt : 2022/4/4
* @Author : Inno Fang
* @Email : innofang@yeah.net
* @Description: Simple implementation of factory method
*/
#include <iostream>
typedef enum ProductType {
TYPE_A,
TYPE_B,
TYPE_C
} ProductType_t;
class ProductInterface {
public:
virtual void use() = 0;
};
class ConcreteProductA : public ProductInterface {
public:
void use() override {
std::cout << "Use productA" << std::endl;
}
};
class ConcreteProductB : public ProductInterface {
public:
void use() override {
std::cout << "Use productB" << std::endl;
}
};
class ConcreteProductC : public ProductInterface {
public:
void use() override {
std::cout << "Use productC" << std::endl;
}
};
class FactoryInterface {
public:
virtual ProductInterface* createProduct(ProductType_t) = 0;
};
class ConcreteFactory : public FactoryInterface {
public:
ProductInterface* createProduct(ProductType_t type) override {
switch (type) {
case TYPE_A:
return new ConcreteProductA();
case TYPE_B:
return new ConcreteProductB();
case TYPE_C:
return new ConcreteProductC();
default:
return nullptr;
}
}
};
int main() {
FactoryInterface *factory = new ConcreteFactory();
ProductInterface *product = factory->createProduct(ProductType_t::TYPE_A);
if (product) product->use();
product = factory->createProduct(ProductType_t::TYPE_B);
if (product) product->use();
product = factory->createProduct(ProductType_t::TYPE_C);
if (product) product->use();
return 0;
}