StatePattern.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <iostream>
  2. using namespace std;
  3. class State;
  4. class ConcreteStateB;
  5. class ConcreteStateA;
  6. class State {
  7. public:
  8. virtual void OperationChangeState(Context*) = 0;
  9. virtual void OperationInterface(Context*) = 0;
  10. virtual ~State() { }
  11. protected:
  12. bool ChangeState(Context* con, State *st) {
  13. con->ChangeState(st);
  14. }
  15. };
  16. class ConcreteStateA :public State {
  17. public:
  18. void OperationChangeState(Context* con) {
  19. OperationInterface(con);
  20. this->ChangeState(con, new ConcreteStateB());
  21. }
  22. void OperationInterface(Context* con) {
  23. cout << "ConcreteStateA::OperationInterface..." << endl;
  24. }
  25. };
  26. class ConcreteStateB :public State {
  27. public:
  28. void OperationChangeState(Context* con) {
  29. OperationInterface(con);
  30. this->ChangeState(con, new ConcreteStateA());
  31. }
  32. void OperationInterface(Context* con) {
  33. cout << "ConcreteStateB::OperationInterface..." << endl;
  34. }
  35. };
  36. class Context {
  37. public:
  38. Context(State* st) {
  39. _st = st;
  40. }
  41. void OperationInterface() {
  42. _st->OperationInterface(this);
  43. }
  44. void OperationChangeState() {
  45. _st->OperationInterface(this);
  46. }
  47. private:
  48. friend class State;
  49. bool ChangeState(State* st) {
  50. _st = st;
  51. return true;
  52. }
  53. State *_st;
  54. };
  55. int main() {
  56. State *st = new ConcreteStateA();
  57. Context *con = new Context(st);
  58. con->OperationInterface();
  59. con->OperationInterface();
  60. con->OperationInterface();
  61. delete con;
  62. delete st;
  63. return 0;
  64. }