fork download
  1. #include <list>
  2. #include <functional>
  3. #include <iostream>
  4.  
  5. template <typename AbstractProduct, typename ConcreteProduct>
  6. inline AbstractProduct *abstractConstructor() {
  7. return new ConcreteProduct();
  8. }
  9.  
  10. template <typename Product>
  11. class Factory {
  12. public:
  13. typedef std::function<Product *()> ConstructorType;
  14. typedef std::list<ConstructorType> RegisteredList;
  15. typedef typename RegisteredList::iterator iterator;
  16.  
  17. static Factory &instance() {
  18. static Factory object;
  19. return object;
  20. }
  21.  
  22. bool add(ConstructorType constructor) {
  23. mRegisteredList.push_back(constructor);
  24.  
  25. return true;
  26. }
  27.  
  28. iterator begin() {
  29. return mRegisteredList.begin();
  30. }
  31.  
  32. iterator end() {
  33. return mRegisteredList.end();
  34. }
  35.  
  36. private:
  37. RegisteredList mRegisteredList;
  38.  
  39. Factory() {};
  40. Factory(const Factory &) = delete;
  41. Factory &operator=(const Factory &) = delete;
  42.  
  43. };
  44.  
  45.  
  46.  
  47. ////////////
  48.  
  49. // Plik register.h
  50. class RegisteredBase // od tej klasy pochodzi dużo różnych klas
  51. {
  52. public:
  53. virtual ~RegisteredBase() {}
  54. virtual void WhoAmI()const=0; // tylko do demonstracji że to działa poprawnie
  55. };
  56.  
  57. typedef Factory<RegisteredBase> Register;
  58.  
  59. // Plik A.h
  60. class A:public RegisteredBase // jedna z tych "różnych klas
  61. {
  62. public:
  63. A() {}
  64. virtual void WhoAmI()const { std::cout<<"class A"<<std::endl; }
  65. };
  66.  
  67. bool reg1 = Register::instance().add(&abstractConstructor<RegisteredBase, A>);
  68.  
  69. // Plik B.h
  70. class B:public RegisteredBase // jeszcze jedna z tych "różnych klas
  71. {
  72. public:
  73. B() {}
  74. virtual void WhoAmI()const { std::cout<<"class B"<<std::endl; }
  75. };
  76.  
  77. bool reg2 = Register::instance().add(&abstractConstructor<RegisteredBase, B>);
  78.  
  79. // Plik C.h
  80. class C:public RegisteredBase // kolejna z tych "różnych klas
  81. {
  82. public:
  83. C() {}
  84. virtual void WhoAmI()const { std::cout<<"class C"<<std::endl; }
  85. };
  86.  
  87. bool reg3 = Register::instance().add(&abstractConstructor<RegisteredBase, C>);
  88.  
  89. /////////////////////////
  90.  
  91. int main() {
  92. std::list<RegisteredBase *> obj;
  93.  
  94. for(Register::iterator it = Register::instance().begin();
  95. it != Register::instance().end();
  96. ++it) {
  97.  
  98. obj.push_back((*it)());
  99. }
  100.  
  101. for(std::list<RegisteredBase *>::iterator it = obj.begin();
  102. it != obj.end();
  103. ++it) {
  104.  
  105. (*it)->WhoAmI();
  106. delete *it;
  107. }
  108.  
  109. return 0;
  110. }
Success #stdin #stdout 0s 3020KB
stdin
Standard input is empty
stdout
class A
class B
class C