State.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <stdio.h>
  2. /*
  3. * C++ Design Patterns: STATE
  4. * http://www.plantuml.com/plantuml/uml/ZP3FIiD04CRlynHpgo8rjCSIGcqfUF9W-mBRpMWZ-oVEpXQB-YwUVGrVpCr8fOA2GqZ2z_s-cPsT9p4isJkeHhZUN6rMEAgWb7Kc9Lp68FGaMA_525rUcz0wEZjly1cmr0NUqcEc98DTT7W5w4g2xumbLF6RrAmo9yqjav1oa_-2qr_1NTSIak_bW9xybZW170yVnsFKAEWRwvSY_1p-fpC52B4u9k7DHEVMswQsqKMUSJmOjt2P6aNhIkMchhRDaTmSUfeD0YveP_PTPEFKMmLh-fGTONbiz7ra8Kz1yECDXSsUE64EkDCTMJDBShb3ss5FkN3lmeI-IqFY8MOUligTn6t9tt_rRGdrDWaej3Wi1VFobxtx1000
  5. *
  6. */
  7. #include <iostream>
  8. class State {
  9. public:
  10. virtual ~State() {}
  11. virtual void Handle() = 0;
  12. };
  13. class ConcreteStateA : public State {
  14. ~ConcreteStateA() {}
  15. void Handle() {
  16. std::cout << "State A handled." << std::endl;
  17. }
  18. };
  19. class ConcreteStateB : public State {
  20. ~ConcreteStateB() {}
  21. void Handle() {
  22. std::cout << "State B handled." << std::endl;
  23. }
  24. };
  25. class Context {
  26. public:
  27. Context() : state() {}
  28. ~Context() {
  29. if (state) {
  30. delete state;
  31. }
  32. }
  33. void setState(State* const s) {
  34. if (state) {
  35. delete state;
  36. }
  37. state = s;
  38. }
  39. void Request() {
  40. std::cout << "call handler()" << std::endl;
  41. state->Handle();
  42. }
  43. private:
  44. State* state;
  45. };
  46. int main() {
  47. Context* context = new Context();
  48. context->setState(new ConcreteStateA());
  49. context->Request();
  50. context->setState(new ConcreteStateB());
  51. context->Request();
  52. }