State Design Pattern �(Behavioral)
Thanh Le – Software Architect / Technical Consultant
Complexity: 1/3
Popularity: 2/3
Intent
State is a behavioral design pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class.
Image source: internet
Problem
Imagine that we have a Document class. A document can be in one of three states: Draft, Moderation and Published. The publish method of the document works a little bit differently in each state:
Image source: internet
Solution
The State pattern suggests that you create new classes for all possible states of an object and extract all state-specific behaviors into these classes.
�Instead of implementing all behaviors on its own, the original object, called context, stores a reference to one of the state objects that represents its current state, and delegates all the state-related work to that object.
�To transition the context into another state, replace the active state object with another object that represents that new state. This is possible only if all state classes follow the same interface and the context itself works with these objects through that interface.
��
Structure
Image source: internet
�
Pros/Cons
�
Practice
https://github.com/thanhle0212/23GoF-Design-Patterns-CSharp