fork download
  1. #include <iostream>
  2.  
  3. // Abstract Product
  4. class AbstractProduct {
  5. public:
  6. virtual ~AbstractProduct() {}
  7. virtual void operation() = 0;
  8. };
  9.  
  10. // Concrete Product 1
  11. class ConcreteProduct1 : public AbstractProduct {
  12. public:
  13. void operation() {
  14. std::cout << "ConcreteProduct1 operation" << std::endl;
  15. }
  16. };
  17.  
  18. // Concrete Product 2
  19. class ConcreteProduct2 : public AbstractProduct {
  20. public:
  21. void operation() {
  22. std::cout << "ConcreteProduct2 operation" << std::endl;
  23. }
  24. };
  25.  
  26. // Abstract Factory
  27. class AbstractFactory {
  28. public:
  29. virtual ~AbstractFactory() {}
  30. virtual AbstractProduct* createProduct() = 0;
  31. };
  32.  
  33. // Concrete Factory 1
  34. class ConcreteFactory1 : public AbstractFactory {
  35. public:
  36. AbstractProduct* createProduct() {
  37. return new ConcreteProduct1();
  38. }
  39. };
  40.  
  41. // Concrete Factory 2
  42. class ConcreteFactory2 : public AbstractFactory {
  43. public:
  44. AbstractProduct* createProduct() {
  45. return new ConcreteProduct2();
  46. }
  47. };
  48.  
  49. // Client
  50. class Client {
  51. private:
  52. AbstractFactory* factory;
  53.  
  54. public:
  55. Client(AbstractFactory* factory) : factory(factory) {}
  56.  
  57. void executeOperation() {
  58. AbstractProduct* product = factory->createProduct();
  59. product->operation();
  60. }
  61. };
  62.  
  63. // Usage
  64. int main() {
  65. AbstractFactory* factory1 = new ConcreteFactory1();
  66. Client* client1 = new Client(factory1);
  67. client1->executeOperation();
  68.  
  69. AbstractFactory* factory2 = new ConcreteFactory2();
  70. Client* client2 = new Client(factory2);
  71. client2->executeOperation();
  72.  
  73. delete factory1;
  74. delete client1;
  75. delete factory2;
  76. delete client2;
  77.  
  78. return 0;
  79. }
  80.  
Success #stdin #stdout 0.01s 5524KB
stdin
Standard input is empty
stdout
ConcreteProduct1 operation
ConcreteProduct2 operation