Repository navigation
Expand file tree
/
Copy pathregistry.cpp
More file actions
86 lines (74 loc) · 2.19 KB
/
Copy pathregistry.cpp
File metadata and controls
86 lines (74 loc) · 2.19 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
85
86
#include <cassert>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
class Chessman {
private:
std::string name_;
protected:
Chessman(std::string name) : name_(name){};
public:
std::string name() { return name_; };
};
class Pawn : public Chessman {
public:
Pawn() : Chessman("pawn"){};
~Pawn() { std::cout << "Pawn dtor\n"; };
static std::shared_ptr<Chessman> create() { return std::make_shared<Pawn>(); }
};
class Bishop : public Chessman {
public:
Bishop() : Chessman("bishop"){};
~Bishop() { std::cout << "Bishop dtor\n"; };
static std::shared_ptr<Chessman> create() {
return std::make_shared<Bishop>();
}
};
class ChessmanRegistry {
public:
static ChessmanRegistry& getInstance() {
static ChessmanRegistry s;
return s;
}
// disable copy in any form
ChessmanRegistry(ChessmanRegistry&) = delete;
ChessmanRegistry& operator=(const ChessmanRegistry&) = delete;
using factoryFunction = std::function<std::shared_ptr<Chessman>()>;
void add(const std::string& name, factoryFunction factory) {
registry_[name] = factory;
};
std::shared_ptr<Chessman> create(const std::string& name) {
if (registry_.find(name) == registry_.end()) {
return nullptr;
}
auto factory = registry_[name];
return factory();
}
private:
std::map<std::string, factoryFunction> registry_;
ChessmanRegistry(){};
};
int main() {
std::cout << "Running registry example\n";
ChessmanRegistry::getInstance().add("pawn", Pawn::create);
std::shared_ptr<Chessman> pawn =
ChessmanRegistry::getInstance().create("pawn");
std::shared_ptr<Chessman> bishop =
ChessmanRegistry::getInstance().create("bishop");
// std::shared_ptr<Chessman> bishop = Chessman::create(BISHOP);
std::cout << "I am pawn: " << pawn->name() << "\n";
if (bishop) {
std::cout << "I am bishop: " << bishop->name() << "\n";
} else {
std::cout << "Bishop not registered!\n";
}
ChessmanRegistry::getInstance().add("bishop", Bishop::create);
bishop = ChessmanRegistry::getInstance().create("bishop");
if (bishop) {
std::cout << "I am bishop: " << bishop->name() << "\n";
} else {
std::cout << "Bishop not registered!\n";
}
return 0;
}