-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory.cc
101 lines (82 loc) · 2.22 KB
/
factory.cc
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
#include <iostream>
#include <memory>
#define simple_factory 0
#define factory_method 1
#if simple_factory
enum class Type { A, B };
// 产品
class Product {
public:
virtual ~Product() { std::cout << " ~Product." << std::endl; };
virtual void Print() const { std::cout << "Product." << std::endl; };
};
class ConcreteProductA : public Product {
public:
~ConcreteProductA() { std::cout << " ~ConcreteProductA." << std::endl; }
void Print() const override { std::cout << "ConcreteProductA." << std::endl; }
};
class ConcreteProductB : public Product {
public:
~ConcreteProductB() { std::cout << " ~ConcreteProductB." << std::endl; }
void Print() const override { std::cout << "ConcreteProductB." << std::endl; }
};
// 工厂
class Factory {
public:
Product* Create(const Type& type) {
switch (type) {
case Type::A:
return new ConcreteProductA;
default:
return new ConcreteProductB;
}
};
};
#endif
#if factory_method
// 产品
class Product {
public:
virtual ~Product() { std::cout << " ~Product." << std::endl; };
virtual void Print() const { std::cout << "Product." << std::endl; };
};
class ConcreteProductA : public Product {
public:
~ConcreteProductA() { std::cout << " ~ConcreteProductA." << std::endl; }
void Print() const override { std::cout << "ConcreteProductA." << std::endl; }
};
class ConcreteProductB : public Product {
public:
~ConcreteProductB() { std::cout << " ~ConcreteProductB." << std::endl; }
void Print() const override { std::cout << "ConcreteProductB." << std::endl; }
};
// 工厂
class Factory {
public:
virtual std::unique_ptr<Factory> Create() = 0;
};
class ConcreteFactoryA : Factory {
public:
std::unique_ptr<Factory> Create() {
return std::unique_ptr<Factory>(new ConcreteFactoryA);
}
};
class ConcreteFactoryB : Factory {
public:
std::unique_ptr<Factory> Create() {
return std::unique_ptr<Factory>(new ConcreteFactoryB);
}
};
#endif
int main() {
#if simple_factory
Factory* f = new Factory();
auto p = f->Create(Type::B);
p->Print();
delete f;
delete p;
#endif
#if factory_method
Factory* f = new Factory();
#endif
}