-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathFlyweightPattern.cpp
More file actions
63 lines (51 loc) · 1.32 KB
/
Copy pathFlyweightPattern.cpp
File metadata and controls
63 lines (51 loc) · 1.32 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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Flyweight {
public:
Flyweight(string state):_state(state) {
}
virtual void Operation(const string&state) { }
string GetState()const { return _state; }
virtual ~Flyweight() { }
private:
string _state;
};
class ConcreteFlyweight :public Flyweight {
public:
ConcreteFlyweight(string state)
:Flyweight(state) {
cout << "ConcreteFlyweight Build..." << state << endl;
}
void Operation(const string& state) {
cout << "ConcreteFlyweight " << GetState() << " \\ " << state << endl;
}
};
class FlyweightFactory {
public:
Flyweight *GetFlyweight(std::string key) {
for (auto fly : _flys) {
if (fly->GetState() == key) {
cout << "already created by users..." << endl;
return fly;
}
}
Flyweight *fn = new ConcreteFlyweight(key);
_flys.push_back(fn);
return fn;
}
private:
std::vector<Flyweight*> _flys;
};
int main() {
FlyweightFactory *fc = new FlyweightFactory();
Flyweight *fw1 = fc->GetFlyweight("hello");
Flyweight *fw2 = fc->GetFlyweight("world");
Flyweight *fw3 = fc->GetFlyweight("hello");
delete fw1;
delete fw2;
//delete fw3;
delete fc;
return 0;
}