-
Notifications
You must be signed in to change notification settings - Fork 961
/
Copy pathPrototype.cpp
116 lines (99 loc) · 1.82 KB
/
Prototype.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
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
/*
* C++ Design Patterns: Prototype
* Author: Jakub Vojvoda [github.com/JakubVojvoda]
* 2016
*
* Source code is licensed under MIT License
* (for more details see LICENSE)
*
*/
#include <iostream>
#include <string>
/*
* Prototype
* declares an interface for cloning itself
*/
class Prototype
{
public:
virtual ~Prototype() {}
virtual Prototype* clone() = 0;
virtual std::string type() = 0;
// ...
};
/*
* Concrete Prototype A and B
* implement an operation for cloning itself
*/
class ConcretePrototypeA : public Prototype
{
public:
~ConcretePrototypeA() {}
Prototype* clone()
{
return new ConcretePrototypeA();
}
std::string type()
{
return "type A";
}
// ...
};
class ConcretePrototypeB : public Prototype
{
public:
~ConcretePrototypeB() {}
Prototype* clone()
{
return new ConcretePrototypeB();
}
std::string type()
{
return "type B";
}
// ...
};
/*
* Client
* creates a new object by asking a prototype to clone itself
*/
class Client
{
public:
static void init()
{
types[ 0 ] = new ConcretePrototypeA();
types[ 1 ] = new ConcretePrototypeB();
}
static void remove()
{
delete types[ 0 ];
delete types[ 1 ];
}
static Prototype* make( const int index )
{
if ( index >= n_types )
{
return nullptr;
}
return types[ index ]->clone();
}
// ...
private:
static Prototype* types[ 2 ];
static int n_types;
};
Prototype* Client::types[ 2 ];
int Client::n_types = 2;
int main()
{
Client::init();
Prototype *prototype1 = Client::make( 0 );
std::cout << "Prototype: " << prototype1->type() << std::endl;
delete prototype1;
Prototype *prototype2 = Client::make( 1 );
std::cout << "Prototype: " << prototype2->type() << std::endl;
delete prototype2;
Client::remove();
return 0;
}