fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <memory>
  4. #include <vector>
  5.  
  6. class IProduct {
  7. public:
  8. virtual std::string Name() = 0;
  9. virtual bool Say() = 0;
  10. virtual ~IProduct() {}
  11. };
  12.  
  13. using Product = std::shared_ptr<IProduct>;
  14.  
  15. class IFactory {
  16. public:
  17. Product Create(const std::string& owner) {
  18. Product p = CreateClass(owner);
  19. RegisterClass(p);
  20. return p;
  21. }
  22. virtual ~IFactory() {}
  23. protected:
  24. virtual Product CreateClass(const std::string&) = 0;
  25. virtual void RegisterClass(Product p) = 0;
  26. };
  27.  
  28. class A : public IProduct {
  29. std::string owner;
  30. public:
  31. A(const std::string& owner) {
  32. this->owner = owner;
  33. }
  34. std::string Name() {
  35. return owner;
  36. }
  37. bool Say() {
  38. std::cout << "Baw " << X << std::endl;
  39. return true;
  40. }
  41. private:
  42. int X = 123;
  43. };
  44.  
  45. class B : public IProduct {
  46. std::string owner;
  47. public:
  48. B(const std::string& owner) {
  49. this->owner = owner;
  50. }
  51. std::string Name() {
  52. return owner;
  53. }
  54. bool Say() {
  55. std::cout << "Maw " << X << std::endl;
  56. return true;
  57. }
  58. protected:
  59. char X = 'b';
  60. };
  61.  
  62. class ClassFactory : public IFactory {
  63. std::vector<std::string> owners;
  64. protected:
  65. Product CreateClass(const std::string& owner) {
  66. if (owner == "A")
  67. return std::make_shared<A>(owner);
  68. else if (owner == "B")
  69. return std::make_shared<B>(owner);
  70. else
  71. return nullptr;
  72. }
  73. void RegisterClass(Product p) {
  74. owners.push_back(p->Name());
  75. }
  76. };
  77.  
  78. int main()
  79. {
  80. auto factory = std::make_shared<ClassFactory>();
  81.  
  82. auto x = factory->Create("A");
  83. std::cout << x->Name() << std::endl;
  84. std::cout << std::boolalpha << x->Say() << std::endl;
  85.  
  86. auto y = factory->Create("B");
  87. std::cout << y->Name() << std::endl;
  88. std::cout << std::boolalpha << y->Say() << std::endl;
  89. }
  90.  
Success #stdin #stdout 0s 4376KB
stdin
Standard input is empty
stdout
A
Baw 123
true
B
Maw b
true