-
Notifications
You must be signed in to change notification settings - Fork 0
/
flyweight.cc
83 lines (67 loc) · 1.67 KB
/
flyweight.cc
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
//
// Design pattern # fly weight
// Flyweight pattern is used to reduce the number of
// objects created.
//
// g++ -std=c++17 -Wall -Wextra -o flyweight flyweight.cc
//
#include <iostream>
#include <unordered_map>
struct Shape {
virtual std::string name() = 0;
virtual void draw() = 0;
};
struct Circle: Shape {
std::string name() override { return "Shape -> Circle"; }
void draw() override { std::cout << "Draw # " << name() << '\n'; }
};
struct Rectangle: Shape {
std::string name() override { return "Shape -> Rectangle"; }
void draw() override { std::cout << "Draw # " << name() << '\n'; }
};
struct Square: Shape {
std::string name() override { return "Shape -> Square"; }
void draw() override { std::cout << "Draw # " << name() << '\n'; }
};
struct Flyweight {
enum class Type {
Circle,
Rectangle,
Square
};
std::unordered_map<Flyweight::Type, Shape*> map;
Shape* get(Flyweight::Type type) {
Shape *sh = map[type];
if (!sh) {
if (type == Type::Circle)
sh = new Circle();
else if (type == Type::Rectangle)
sh = new Rectangle();
else if (type == Type::Square)
sh = new Square();
map[type] = sh;
}
return sh;
}
void show() {
std::cout << "Available objects: \n";
for(const std::pair<const Flyweight::Type, Shape *> n: map) {
std::cout << " " << n.second->name() << '\n';
}
}
};
//
// Entry function
//
int main() {
std::cout << "Design pattern # flyweight\n";
Flyweight fw;
Shape *s = fw.get(Flyweight::Type::Circle);
s->draw();
s = fw.get(Flyweight::Type::Square);
s->draw();
fw.show();
s = fw.get(Flyweight::Type::Square);
s->draw();
return 0;
}