|
| 1 | +#include <iostream> |
| 2 | +#include <typeinfo> |
| 3 | +/** |
| 4 | + * EN: State Design Pattern |
| 5 | + * |
| 6 | + * Intent: Lets an object alter its behavior when its internal state changes. It |
| 7 | + * appears as if the object changed its class. |
| 8 | + * |
| 9 | + * RU: Паттерн Состояние |
| 10 | + * |
| 11 | + * Назначение: Позволяет объектам менять поведение в зависимости от своего |
| 12 | + * состояния. Извне создаётся впечатление, что изменился класс объекта. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * EN: The base State class declares methods that all Concrete State should |
| 17 | + * implement and also provides a backreference to the Context object, associated |
| 18 | + * with the State. This backreference can be used by States to transition the |
| 19 | + * Context to another State. |
| 20 | + * |
| 21 | + * RU: Базовый класс Состояния объявляет методы, которые должны реализовать все |
| 22 | + * Конкретные Состояния, а также предоставляет обратную ссылку на объект |
| 23 | + * Контекст, связанный с Состоянием. Эта обратная ссылка может использоваться |
| 24 | + * Состояниями для передачи Контекста другому Состоянию. |
| 25 | + */ |
| 26 | + |
| 27 | +class Context; |
| 28 | + |
| 29 | +class State |
| 30 | +{ |
| 31 | + /** |
| 32 | + * @var Context |
| 33 | + */ |
| 34 | +protected: |
| 35 | + Context *context_; |
| 36 | + |
| 37 | +public: |
| 38 | + virtual ~State() |
| 39 | + { |
| 40 | + } |
| 41 | + |
| 42 | + void set_context(Context *context) |
| 43 | + { |
| 44 | + this->context_ = context; |
| 45 | + } |
| 46 | + |
| 47 | + virtual void Handle1() = 0; |
| 48 | + virtual void Handle2() = 0; |
| 49 | +}; |
| 50 | + |
| 51 | +/** |
| 52 | + * EN: The Context defines the interface of interest to clients. It also |
| 53 | + * maintains a reference to an instance of a State subclass, which represents |
| 54 | + * the current state of the Context. |
| 55 | + * |
| 56 | + * RU: Контекст определяет интерфейс, представляющий интерес для клиентов. Он |
| 57 | + * также хранит ссылку на экземпляр подкласса Состояния, который отображает |
| 58 | + * текущее состояние Контекста. |
| 59 | + */ |
| 60 | +class Context |
| 61 | +{ |
| 62 | + /** |
| 63 | + * EN: @var State A reference to the current state of the Context. |
| 64 | + * |
| 65 | + * RU: @var State Ссылка на текущее состояние Контекста. |
| 66 | + */ |
| 67 | +private: |
| 68 | + State *state_; |
| 69 | + |
| 70 | +public: |
| 71 | + Context(State *state) : state_(nullptr) |
| 72 | + { |
| 73 | + this->TransitionTo(state); |
| 74 | + } |
| 75 | + ~Context() |
| 76 | + { |
| 77 | + delete state_; |
| 78 | + } |
| 79 | + /** |
| 80 | + * EN: The Context allows changing the State object at runtime. |
| 81 | + * |
| 82 | + * RU: Контекст позволяет изменять объект Состояния во время выполнения. |
| 83 | + */ |
| 84 | + void TransitionTo(State *state) |
| 85 | + { |
| 86 | + std::cout << "Context: Transition to " << typeid(*state).name() << ".\n"; |
| 87 | + if (this->state_ != nullptr) |
| 88 | + delete this->state_; |
| 89 | + this->state_ = state; |
| 90 | + this->state_->set_context(this); |
| 91 | + } |
| 92 | + /** |
| 93 | + * EN: The Context delegates part of its behavior to the current State |
| 94 | + * object. |
| 95 | + * |
| 96 | + * RU: Контекст делегирует часть своего поведения текущему объекту |
| 97 | + * Состояния. |
| 98 | + */ |
| 99 | + void Request1() |
| 100 | + { |
| 101 | + this->state_->Handle1(); |
| 102 | + } |
| 103 | + void Request2() |
| 104 | + { |
| 105 | + this->state_->Handle2(); |
| 106 | + } |
| 107 | +}; |
| 108 | + |
| 109 | +/** |
| 110 | + * EN: Concrete States implement various behaviors, associated with a state of |
| 111 | + * the Context. |
| 112 | + * |
| 113 | + * RU: Конкретные Состояния реализуют различные модели поведения, связанные с |
| 114 | + * состоянием Контекста. |
| 115 | + */ |
| 116 | + |
| 117 | +class ConcreteStateA : public State |
| 118 | +{ |
| 119 | +public: |
| 120 | + void Handle1() override; |
| 121 | + |
| 122 | + void Handle2() override |
| 123 | + { |
| 124 | + std::cout << "ConcreteStateA handles request2.\n"; |
| 125 | + } |
| 126 | +}; |
| 127 | + |
| 128 | +class ConcreteStateB : public State |
| 129 | +{ |
| 130 | +public: |
| 131 | + void Handle1() override |
| 132 | + { |
| 133 | + std::cout << "ConcreteStateB handles request1.\n"; |
| 134 | + } |
| 135 | + void Handle2() override |
| 136 | + { |
| 137 | + std::cout << "ConcreteStateB handles request2.\n"; |
| 138 | + std::cout << "ConcreteStateB wants to change the state of the context.\n"; |
| 139 | + this->context_->TransitionTo(new ConcreteStateA); |
| 140 | + } |
| 141 | +}; |
| 142 | + |
| 143 | +void ConcreteStateA::Handle1() |
| 144 | +{ |
| 145 | + { |
| 146 | + std::cout << "ConcreteStateA handles request1.\n"; |
| 147 | + std::cout << "ConcreteStateA wants to change the state of the context.\n"; |
| 148 | + |
| 149 | + this->context_->TransitionTo(new ConcreteStateB); |
| 150 | + } |
| 151 | +} |
| 152 | + |
| 153 | +/** |
| 154 | + * EN: The client code. |
| 155 | + * |
| 156 | + * RU: Клиентский код. |
| 157 | + */ |
| 158 | +void ClientCode() |
| 159 | +{ |
| 160 | + Context *context = new Context(new ConcreteStateA); |
| 161 | + context->Request1(); |
| 162 | + context->Request2(); |
| 163 | + delete context; |
| 164 | +} |
| 165 | + |
| 166 | +int main() |
| 167 | +{ |
| 168 | + ClientCode(); |
| 169 | + return 0; |
| 170 | +} |
0 commit comments