State Pattern

State Pattern is a #Design Pattern which allows an object to alter its behaviours based on its internal state changes. It is not possible to establish such operations without the design pattern due to the immutability of a running object. By following the design pattern, the object could be able to change its behaviour according to the state change during its lifetime and be extended with new states without affecting the existing states.

Implementing the State Pattern onto a class could be done by encapsulate each state of the class into another independent class which will be in composition of the old class. The old class will change its state via a superclass of the state classes which provides an abstraction over different kind of states that the class could go through. The superclass should be the parent for the newly created state classes.

Links to this page
  • Refactoring: Improving The Design of Existing Code

    If there’s a need to change the object’s state or behaviour during the lifetime, refactor the class to adhere the State Pattern# will be a good idea. This is especially useful on the classes that involves switch or other conditional statement in order to provide different services based on its current state. It eliminates the need for conditional statement and type code, and instead relies on polymorphism to do the job.

    Type codes usually show a bad smell in code. Replace them with either class (if it doesn’t affect the behaviour), subclasses or State Pattern# or Strategy Pattern (the latter is useful in replacing conditional codes such as switch statement). Usually, polymorphism is the cure to the symptom, but it could be an overkill. If they effect on a single method, replacing them with explicit methods could do the job well. If one of the conditional cases is null, then introduce a Null Object Pattern#.

  • Design Pattern
#oop #refactoring