The State design pattern is a behavioral pattern that allows an object to change its behavior when its internal state changes. This pattern encapsulates state-specific behavior and transitions inside state objects, making it easy to add or modify states without altering the context object.
Understanding the Template Method Design Pattern in C#
Example without State Design Pattern
Let's consider a scenario where we have a Document
class that can be in different states: Draft, Moderation, and Published. Each state defines specific behavior for the Publish
and Edit
actions.
using System; namespace WithoutStatePattern { // Context class class Document { public string State { get; private set; } public Document() { State = "Draft"; } public void Publish() { if (State == "Draft") { Console.WriteLine("Document is in Draft state and is being sent for moderation."); State = "Moderation"; } else if (State == "Moderation") { Console.WriteLine("Document is in Moderation state and is being published."); State = "Published"; } else if (State == "Published") { Console.WriteLine("Document is already published."); } } public void Edit() { if (State == "Draft") { Console.WriteLine("Document is in Draft state and is being edited."); } else if (State == "Moderation") { Console.WriteLine("Document is in Moderation state and cannot be edited."); } else if (State == "Published") { Console.WriteLine("Document is published and cannot be edited."); } } } class Program { static void Main(string[] args) { Document document = new Document(); document.Edit(); document.Publish(); document.Edit(); document.Publish(); document.Publish(); } } }
Problems in the Non-Pattern Approach
- Complex Conditional Logic:The
Publish
andEdit
methods contain complex conditional logic to handle the different states. As the number of states grows, the complexity of these methods will increase, making the code harder to read and maintain. - Scalability Issues:Adding new states or modifying existing states requires changes to the conditional logic in multiple methods. This makes the code less flexible and harder to extend.
- Violation of Single Responsibility Principle:The
Document
class is responsible for both state management and business logic. This violates the Single Responsibility Principle, making the class harder to maintain and evolve. - Lack of Encapsulation:The state management logic is not encapsulated within individual state classes. Instead, it is spread across multiple methods in the
Document
class, leading to code duplication and potential inconsistencies.
- Encapsulation:The State Pattern encapsulates state-specific behavior within individual state classes. This keeps the state management logic localized and prevents it from spreading across multiple methods in the
Document
class. - Single Responsibility:The
Document
class is responsible only for state transitions, while each state class handles the behavior specific to that state. This separation of concerns leads to cleaner and more maintainable code. - Scalability and Flexibility:Adding new states or modifying existing states requires changes only in the corresponding state classes. The
Document
class remains unchanged, making the system more flexible and easier to extend. - Simplified Conditional Logic:The complex conditional logic in the
Publish
andEdit
methods is replaced by polymorphism. Each state class implements the state-specific behavior, simplifying theDocument
class and improving readability.
Revisited Code with State Pattern
Here is how we can implement this pattern :
using System; namespace StatePattern { // Context class class Document { private IDocumentState _state; public Document() { _state = new DraftState(); } public void SetState(IDocumentState state) { _state = state; } public void Publish() { _state.Publish(this); } public void Edit() { _state.Edit(this); } } // State interface interface IDocumentState { void Publish(Document document); void Edit(Document document); } // Concrete state for Draft class DraftState : IDocumentState { public void Publish(Document document) { Console.WriteLine("Document is in Draft state and is being sent for moderation."); document.SetState(new ModerationState()); } public void Edit(Document document) { Console.WriteLine("Document is in Draft state and is being edited."); } } // Concrete state for Moderation class ModerationState : IDocumentState { public void Publish(Document document) { Console.WriteLine("Document is in Moderation state and is being published."); document.SetState(new PublishedState()); } public void Edit(Document document) { Console.WriteLine("Document is in Moderation state and cannot be edited."); } } // Concrete state for Published class PublishedState : IDocumentState { public void Publish(Document document) { Console.WriteLine("Document is already published."); } public void Edit(Document document) { Console.WriteLine("Document is published and cannot be edited."); } } class Program { static void Main(string[] args) { Document document = new Document(); document.Edit(); document.Publish(); document.Edit(); document.Publish(); document.Publish(); } } }
Why Can't We Use Other Design Patterns Instead?
- Strategy Pattern: The Strategy pattern defines a family of algorithms and allows the client to choose which algorithm to use. It does not manage state transitions and dynamic behavior changes based on state.
- Observer Pattern: The Observer pattern defines a one-to-many dependency between objects, where one object notifies its dependents of state changes. It is not designed for managing state-specific behavior and transitions.
- Template Method Pattern: The Template Method pattern defines the structure of an algorithm but allows subclasses to override certain steps. It does not handle dynamic state transitions.
Steps to Identify Use Cases for the State Pattern
- Identify State-Dependent Behaviour: Look for scenarios where an object's behaviour changes based on its state.
- Encapsulation of States: Ensure that state-specific behaviour can be encapsulated in separate state classes.
- Dynamic State Transitions: Consider the State pattern when the object needs to transition between different states dynamically.
- Promote Maintainability: Use the State pattern to improve maintainability by isolating state-specific behaviour.
By following these steps and implementing the State pattern, you can achieve dynamic behavior changes based on an object's state, encapsulate state-specific behavior, and improve maintainability in your system.
Comments
Post a Comment