-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactoryMethod.cpp
More file actions
122 lines (97 loc) · 2.47 KB
/
factoryMethod.cpp
File metadata and controls
122 lines (97 loc) · 2.47 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
What is factory method?
Parent class provides a factory method. Derived class can overwrite the factory method to create (new operator) different objects.
1. In parent class (creator), factory method is defined.
2. Derived class of creator includes overwrite factory method.
3. Differ concrete product is new-ed in the factory methods.
4. When need to add new product to current system, 1) add derived class of creator; 2) add new product class
No need new a product class object in client code.
Client code only need minor changes.
*/
#include <iostream>
using namespace std;
// parent class of product
// Abstract class, defines product common interface
class product
{
public:
virtual ~product() {};
virtual string identifier() const = 0;
};
// product 1
class product1 : public product
{
public:
string identifier() const override
{
return "I am product 1.";
}
};
// product 2
class product2 : public product
{
public:
string identifier() const override
{
return "I am product 2.";
}
};
// Parent class definition -- creator
// Abstract class, is responsible to define interface of factory method
class creator
{
public:
creator() {};
virtual ~creator() {};
// pure virtual function, must realize in derived class.
virtual product *factoryMethod() const = 0;
string demo() const
{
product *pdt = this->factoryMethod();
string re = pdt->identifier();
delete pdt;
return re;
}
};
// 1 derived class of creator
// Responsible for concrete product creation
class creator1 : public creator
{
public:
//overwrite factory method
// use abstract class 'product' so that creator can be independent with product1...
product *factoryMethod() const override
{
return new product1();
}
};
// 2 derived class of creator
// Responsible for concrete product creation
class creator2 : public creator
{
public:
//overwrite factory method
// use abstract class 'product' so that creator can be independent with product2...
product *factoryMethod() const override
{
return new product2();
}
};
// client code for demo
void clientCode(const creator & crt)
{
cout << crt.demo() << endl;
}
int main()
{
cout << "create create1 " << endl;
creator *crt1 = new creator1();
clientCode(*crt1);
cout << endl;
cout << "create create2 " << endl;
creator *crt2 = new creator2();
clientCode(*crt2);
delete crt1;
delete crt2;
return 0;
}