|
1 |
| -# TODO |
| 1 | +Also known as **Objects for states**. |
2 | 2 |
|
3 |
| -Stay tuned, this section will be completed shortly ! |
| 3 | +# Intend |
| 4 | + |
| 5 | +As stated in [_GoF_, p305](https://fr.wikipedia.org/wiki/Design_Patterns) : |
| 6 | +> Allow an object to alter its behaviour when its internal state changes. The object ill appear to change its class. |
| 7 | +
|
| 8 | +You should use the _State_ pattern in the following cases : |
| 9 | + - You want to change an object's behaviour at runtime depending on its state. |
| 10 | + - When you have a class polluted with massive conditionals that alter how it behaves. |
| 11 | + - When you have a lot of duplicate code across similar states and transitions of a condition-based state machine. |
| 12 | + |
| 13 | +# How it's done |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +**Participants** |
| 18 | + |
| 19 | + -_Context_ |
| 20 | + - Interface of interest to clients. |
| 21 | + - Maintains an instance of a _ConcreteState_ subclass that defines the current state and its behaviour. |
| 22 | + - _State_ Interface for the behaviour associated with a particular state of the _Context_. |
| 23 | + - _ConcreteStates_ implement a behaviour associated with a state of the _Context_. |
| 24 | + |
| 25 | +**How to implement** |
| 26 | + |
| 27 | + 1. **Declare** the _State_ interface - that is, the behaviour that depends on the state. |
| 28 | + 2. **Create** a _ConcreteState_ subclass for every identified state of the _Context_. Implement the behaviours of those states. |
| 29 | + 3. **Add** a reference field of the _State_ in the _Context_ class and its associated setter. |
| 30 | + 4. **Replace** where needed in the methods of the _Context_ the conditionals with the corresponding calls to the _State_ object. |
| 31 | + |
| 32 | + |
| 33 | +Note : UML class diagram taken from [**here**](https://upload.wikimedia.org/wikipedia/commons/e/ec/W3sDesign_State_Design_Pattern_UML.jpg) |
| 34 | + |
| 35 | +# Pros & cons |
| 36 | + |
| 37 | +**Pros** |
| 38 | + |
| 39 | + - **Open/Closed principle** : It is easy to introduce new _ConcreteStates_ without breaking any existing code. |
| 40 | + - **Single responsability principle** : Separate states/behaviours are defined within separate classes. |
| 41 | + - Simplify the code of the _Context_ by eliminating a lot of conditionals. |
| 42 | + |
| 43 | +**Cons** |
| 44 | + |
| 45 | + - Can be overkill if there are only a few states and they should never change. |
| 46 | + |
| 47 | +# Notes |
| 48 | + |
| 49 | +Here are some _usefull ressources_ : |
| 50 | + - [**w3sdesign**](http://w3sdesign.com/#gf) |
| 51 | + - A [**Refactoring guru**](https://refactoring.guru/design-patterns/state) article. |
| 52 | + - A complete example [**here**](http://www.vishalchovatiya.com/state-design-pattern-in-modern-cpp/) |
0 commit comments