-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflyweight design pattern.cpp
More file actions
64 lines (52 loc) · 1.59 KB
/
Copy pathflyweight design pattern.cpp
File metadata and controls
64 lines (52 loc) · 1.59 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
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
// Flyweight Interface
class Flyweight {
public:
virtual void operation(const string& extrinsicState) const = 0;
virtual ~Flyweight() = default;
};
// Concrete Flyweight
class ConcreteFlyweight : public Flyweight {
private:
string intrinsicState;
public:
ConcreteFlyweight(const string& state) : intrinsicState(state) {}
void operation(const string& extrinsicState) const override {
cout << "ConcreteFlyweight: Intrinsic State = " << intrinsicState
<< ", Extrinsic State = " << extrinsicState << endl;
}
};
// Flyweight Factory
class FlyweightFactory {
private:
unordered_map<string, Flyweight*> flyweights;
public:
~FlyweightFactory() {
for (auto pair : flyweights) {
delete pair.second;
}
}
Flyweight* getFlyweight(const string& key) {
if (flyweights.find(key) == flyweights.end()) {
flyweights[key] = new ConcreteFlyweight(key);
cout << "Creating new flyweight for key: " << key << endl;
} else {
cout << "Reusing existing flyweight for key: " << key << endl;
}
return flyweights[key];
}
};
// Client code
int main() {
FlyweightFactory factory;
Flyweight* flyweight1 = factory.getFlyweight("State1");
flyweight1->operation("Extrinsic1");
Flyweight* flyweight2 = factory.getFlyweight("State2");
flyweight2->operation("Extrinsic2");
Flyweight* flyweight3 = factory.getFlyweight("State1");
flyweight3->operation("Extrinsic3");
return 0;
}