forked from JakubVojvoda/design-patterns-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrototype.cpp
More file actions
84 lines (72 loc) · 1.35 KB
/
Copy pathPrototype.cpp
File metadata and controls
84 lines (72 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
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* 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>
/*
* Prototype
* declares an interface for cloning itself
*/
class Prototype {
public:
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:
Prototype *clone() {
return new ConcretePrototypeA;
}
std::string type() {
return "type A";
}
// ...
};
class ConcretePrototypeB : public Prototype {
public:
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 Prototype* make(int index) {
return types[index]->clone();
}
// ...
private:
static Prototype* types[2];
};
Prototype* Client::types[] =
{
new ConcretePrototypeA,
new ConcretePrototypeB
// ...
};
int main()
{
Prototype* prototype;
prototype = Client::make(0);
std::cout << "Prototype: " << prototype->type() << std::endl;
prototype = Client::make(1);
std::cout << "Prototype: " << prototype->type() << std::endl;
return 0;
}