Prototype.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <stdio.h>
  2. /*
  3. * C++ Design Patterns: PROTOTYPE
  4. * http://www.plantuml.com/plantuml/uml/XP71JW8n48RlVOf9F2nerWqSoMP395w5A1TFf5i6hUcspNHAGjHtySfpy6BM1fQ39CnfC__t_pEpdGQMnB4peYfWyJnVpfUlYqSeAf5AMqRQI8Mm8CUETnxXKq2g6r36MHmCnRSGoiWGO6OqMZxgTn2GUzFWRB_rmmoKu4bl9UFAdxIZKUMSrVzyPnKXOvyrwcTTPyUNs7UzHi3Eymuwx5ga8CJnYh9ipZUBy_hrLrbUsEGgCHR2EaQG0Pv6UPEwRMhbZAC9kPqq3oPYq-DrbQMchjhcH2zJV_BNW1cXPEsiD5bxyOUzqXkDO0hNVY23bmJHWd8sC4N560ciwxh37ef-Hf7DYTQ9abOb_ne3v8G0XnzWabiaC9Z_cNnBUeJ-jUu5sZLOnoYcwIjsvXS0
  5. *
  6. */
  7. #include <iostream>
  8. #include <string>
  9. class Prototype {
  10. public:
  11. Prototype() { std::cout << "Constructor Prototype" << std::endl; }
  12. virtual ~Prototype() {std::cout << "Destructor Prototype" << std::endl;}
  13. virtual Prototype* clone() = 0;
  14. virtual void checkPrototype() = 0;
  15. };
  16. class ConcretePrototype1 : public Prototype {
  17. public:
  18. ConcretePrototype1() { std::cout << "Constructor ConcretePrototype1" << std::endl; }
  19. ~ConcretePrototype1() {std::cout << "Destructor ConcretePrototype1" << std::endl;}
  20. Prototype* clone() { std::cout << "Clone ConcretePrototype1" << std::endl; return new ConcretePrototype1; }
  21. void checkPrototype() { std::cout << "Prototype1 has been created" << std::endl; }
  22. };
  23. class ConcretePrototype2 : public Prototype {
  24. public:
  25. ConcretePrototype2() { std::cout << "Constructor ConcretePrototype2" << std::endl; }
  26. ~ConcretePrototype2() {std::cout << "Destructor ConcretePrototype2" << std::endl;}
  27. Prototype* clone() { std::cout << "Clone ConcretePrototype2" << std::endl; return new ConcretePrototype2; }
  28. void checkPrototype() { std::cout << "Prototype2 has been created" << std::endl; }
  29. };
  30. class Client {
  31. public:
  32. Client() { private_prototype = nullptr; std::cout << "Constructor Client" << std::endl; }
  33. ~Client() {
  34. if (private_prototype) {
  35. delete private_prototype;
  36. }
  37. }
  38. void setPrototype(Prototype *p) {
  39. std::cout << "Client setPrototype" << std::endl;
  40. if (private_prototype) {
  41. delete private_prototype;
  42. }
  43. private_prototype = p;
  44. }
  45. Prototype* client_clone() {
  46. if (!private_prototype) {
  47. return nullptr;
  48. }
  49. std::cout << "Clone() Client" << std::endl;
  50. return private_prototype->clone();
  51. }
  52. private:
  53. Prototype *private_prototype;
  54. };
  55. int main(int argc, char* argv[]) {
  56. Client client;
  57. client.setPrototype(new ConcretePrototype1);
  58. Prototype *p1 = client.client_clone();
  59. p1->checkPrototype();
  60. client.setPrototype(new ConcretePrototype2);
  61. Prototype *p2 = client.client_clone();
  62. p2->checkPrototype();
  63. }