StrategyPattern.cpp 748 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <iostream>
  2. using namespace std;
  3. class Strategy {
  4. public:
  5. virtual void Interface() = 0;
  6. virtual ~Strategy() { }
  7. };
  8. class ConcreteStrategyA :public Strategy {
  9. public:
  10. void Interface() {
  11. cout << "ConcreteStrategyA::Interface..." << endl;
  12. }
  13. };
  14. class ConcreteStrategyB :public Strategy {
  15. public:
  16. void Interface() {
  17. cout << "ConcreteStrategyB::Interface..." << endl;
  18. }
  19. };
  20. class Context {
  21. public:
  22. Context(Strategy *stg) {
  23. _stg = stg;
  24. }
  25. void DoAction() {
  26. _stg->Interface();
  27. }
  28. private:
  29. Strategy *_stg;
  30. };
  31. int main() {
  32. Strategy *ps = new ConcreteStrategyA();
  33. Context *pc = new Context(ps);
  34. pc->DoAction();
  35. delete pc;
  36. delete ps;
  37. return 0;
  38. }