Factory_Method.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * C++ Design Patterns: FACTORY METHOD
  3. * http://www.plantuml.com/plantuml/uml/RL3DJZen4B_tAIRv7_WRXOrNijcW8F4WOWmNZztkA3LjXqpRmqPz89w35xEK1SF77Fenlu_v6FaWEKHhHD63wTruCNzzWzd3ud4-WLuXKYWZlOSnemp4y2KWnJzubofzsnc69JN_hyJFWKXECGOy5bnV4cWNa5CUuOMfYIeSt3tPnDFkemCk5UWW8PQwGK2x2YrOj3Mo5s9lM7xt-sUAhhLZi4kA4pAKWpEAS1GGf8VdsznlMLUb8aCyP6gbkJSHg-bkNDZDMnOPhygYhlQIHRl2uJQnswqc9qt69fkrOXqWEeI_5QqeCYZUh94J0bH_OhZ9V2kr1vCEZ-a2Jz7tyweGccIb6-H19ZxrjFD1EgLpEK0VG2r9Uvti9P-81m9T0zjHnIYzeZM_
  4. *
  5. * 2021 / JMB
  6. *
  7. */
  8. #include <iostream>
  9. #include <string>
  10. class Product {
  11. public:
  12. Product() { std::cout << "Product instancied" << std::endl; }
  13. virtual ~Product() {}
  14. virtual void somethingProduct() = 0;
  15. };
  16. class ConcreateProductA : public Product {
  17. public:
  18. ConcreateProductA() { std::cout << "ConcreateProductA instancied" << std::endl; }
  19. ~ConcreateProductA() {}
  20. void somethingProduct() { std::cout << "ProductA has been created" << std::endl; }
  21. };
  22. class ConcreateProductB : public Product {
  23. public:
  24. ConcreateProductB() { std::cout << "ConcreateProductB instancied" << std::endl; }
  25. ~ConcreateProductB() {}
  26. void somethingProduct() { std::cout << "ProductB has been created" << std::endl; }
  27. };
  28. class Creator {
  29. public:
  30. Creator() { std::cout << "Creator instancied" << std::endl; }
  31. virtual ~Creator() {}
  32. virtual Product* factoryMethod() = 0;
  33. };
  34. class ConcreateCreator : public Creator {
  35. public:
  36. enum TProduct { A, B};
  37. TProduct private_a;
  38. ConcreateCreator( TProduct b) { std::cout << "ConcreateCreator instancied" << std::endl; private_a=b; }
  39. ~ConcreateCreator() {}
  40. Product* factoryMethod() {
  41. if (private_a==A) {
  42. return new ConcreateProductA; }
  43. else if (private_a==B) {
  44. return new ConcreateProductB; }
  45. else return 0;
  46. }
  47. };
  48. int main(int argc, char* argv[]) {
  49. Creator *creator = new ConcreateCreator(ConcreateCreator::A);
  50. Product *productA = creator->factoryMethod();
  51. productA->somethingProduct();
  52. Product *productB = creator->factoryMethod();
  53. productB->somethingProduct();
  54. }