Strategy.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <stdio.h>
  2. /*
  3. * C++ Design Patterns: STRATEGY
  4. * http://www.plantuml.com/plantuml/uml/bP3FIiD04CRlynHpgw8rU2qXj57nvi7cud6ocIOB-oTiPgL1VQ0-Hr_CRJ15K12_q_9zluKVinw4WaHh85lWjdhUL0-FBxZ884KP6WQyyqvuBm3Q2OSTASQj119kHtm3JBb2thEAmXUNyF7jcmeiFBER_y3bxt2d6qQslOnesTOS1e0lFVJBvTaBpeBvUwf_gFonbm3E2oCD-7GxUUHraIjlV5W5Fv8fJUHYflDiMeeyguiPhiQULwS2I-xeLVj0PjhkZuUTTbemEYJJ-g2bitoDXZ6mQoPckhFgoBLCTHfOKjKS3tq2o0as4PNHxEG6KeCdLLYdLxJc4m00
  5. *
  6. */
  7. #include <iostream>
  8. class Strategy {
  9. public:
  10. virtual ~Strategy() {}
  11. virtual void execute() = 0;
  12. };
  13. class ConcreteStrategyA : public Strategy {
  14. ~ConcreteStrategyA() {}
  15. void execute() {
  16. std::cout << "Concrete Strategy A" << std::endl;
  17. }
  18. };
  19. class ConcreteStrategyB : public Strategy {
  20. ~ConcreteStrategyB() {}
  21. void execute() {
  22. std::cout << "Concrete Strategy B" << std::endl;
  23. }
  24. };
  25. class ConcreteStrategyC : public Strategy {
  26. ~ConcreteStrategyC() {}
  27. void execute() {
  28. std::cout << "Concrete Strategy C" << std::endl;
  29. }
  30. };
  31. class Context {
  32. public:
  33. Context(Strategy* s) : strategy(s) {
  34. std::cout << "Assign Concrete Strategy : " << typeid(*s).name() << std::endl;
  35. }
  36. ~Context() {
  37. delete strategy;
  38. }
  39. void execute() {
  40. strategy->execute();
  41. }
  42. private:
  43. Strategy* strategy;
  44. };
  45. int main() {
  46. Context context(new ConcreteStrategyB());
  47. context.execute();
  48. }