From time to time it's need to make support for states for objects. As I understand there are two approaches:
it's evident that need to use State pattern for such purposes(I am not sure).
But reading other code I often face with enum only not state pattern at all. Does state pattern has power?
Disadvantages. The State pattern requires a lot of code to be written. Depending on how many different state transition methods are defined, and how many possible states an object can be in, there can quickly be dozens or more different methods that must be written.
Singleton Design Pattern is one of GOF (Gang of Four) design pattern. It comes under creational patterns. The main idea behind the Singleton is, create only one object of a specific class is ever created.
The state pattern is used in computer programming to encapsulate varying behavior for the same object, based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.
State design pattern is one of the behavioral design pattern. State design pattern is used when an Object change its behavior based on its internal state.
Why do we use State pattern? To remove conditional logic duplication, and replace conditional code with polymorphism.
When do we have conditional logic duplication? When we have many actions, which depend on state, thus you have to duplicate your conditional logic in every action. It becomes very annoying when you have many states. Also code duplication means that you should update every copy of duplicated code when you are adding new states.
So, if I don't have duplicated conditional logic, I'd rather go with enum-based state, instead of creating new class hierarchy with many classes for states. Sometimes I even prefer conditional logic duplication: e.g. when I have many states, but only few state-dependent actions. In this case I prefer to have two switch blocks instead of creating ten new classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With