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
|
#include <iostream>
#include <string>
#include <map>
struct A; struct AChild; struct B; struct BChild; struct C; struct D; struct E;
struct System {
static const std::map<std::string, A*> prototypes;
static std::map<std::string, A*> initializePrototypes();
};
const std::map<std::string, A*> System::prototypes = initializePrototypes();
struct A {
const std::string name;
AChild* child;
A (const std::string& n) : name(n) {}
A (const std::string& n, AChild* newChild) : name(n), child(newChild) {}
};
struct AChild : A {using A::A;};
struct B : AChild {
BChild* child;
using AChild::AChild;
B (const std::string& n, BChild* newChild) : AChild(n), child(newChild) {}
};
struct BChild : B {using B::B;};
struct C : public BChild {
static C* getInstance() {static C* c = new C("C"); return c;} // singleton because it's a leaf
private:
C (const std::string& n) : BChild(n) {}
};
struct D : BChild {
static D* getInstance() {static D* d = new D("D"); return d;} // singleton because it's a leaf
private:
D (const std::string& n) : BChild(n) {}
};
struct E : AChild {
static E* getInstance() {static E* e = new E("E"); return e;} // singleton because it's a leaf
using AChild::AChild;
private:
E (const std::string& n) : AChild(n) {}
};
std::map<std::string, A*> System::initializePrototypes() {
std::map<std::string, A*> map;
B *bc = new B("B-C", C::getInstance()), *bd = new B("B-D", C::getInstance());
A *abc = new A("A-B-C", bc), *abd = new A("A-B-D", bd), *ae = new A("A-E", E::getInstance());
map.emplace(abc->name, abc);
map.emplace(abd->name, abd);
map.emplace(ae->name, ae);
return map;
}
int main() {
for (const auto& x : System::prototypes)
std::cout << x.first << ", " << x.second << std::endl;
std::cin.get();
}
/* Output:
A-B-C, 0x652a48
A-B-D, 0x652a78
A-E, 0x652ac8
*/
|