1ae1de6d0d2a87e6834da409bfd891b2 Behavioural design pattern (strategy ,state) with python implementation

Behavioural design pattern (strategy ,state) with python implementation

 Behavioral design patterns are a category of design patterns in software engineering that focus on how objects interact and communicate with each other. These patterns help in defining clear communication protocols between objects and ensure that these interactions are flexible and extensible.





🔑 Key Purpose:

To improve communication between objects and manage responsibilities effectively.


📚 Common Behavioral Design Patterns:

  1. Chain of Responsibility
    Passes a request along a chain of handlers. Each handler decides either to process the request or to pass it on.
    Example: Logging system with different log levels (INFO → DEBUG → ERROR).

  2. Command
    Encapsulates a request as an object, allowing you to parameterize clients with different requests.
    Example: Undo/Redo functionality in a text editor.

  3. Interpreter
    Defines a grammar for interpreting expressions in a language and uses an interpreter object to interpret sentences.
    Example: SQL or mathematical expression evaluators.

  4. Iterator
    Provides a way to access elements of a collection sequentially without exposing its underlying representation.
    Example: foreach loops.

  5. Mediator
    Encapsulates how a set of objects interact, promoting loose coupling.
    Example: Chatroom where users communicate through a central hub.

  6. Memento
    Captures and restores an object’s internal state without violating encapsulation.
    Example: Saving and restoring game progress.

  7. Observer
    Defines a one-to-many dependency so that when one object changes state, all its dependents are notified automatically.
    Example: Event listeners in UI frameworks.

  8. State
    Allows an object to alter its behavior when its internal state changes.
    Example: Vending machine or traffic light controller.

  9. Strategy
    Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
    Example: Sorting strategies like quicksort, mergesort, etc.

  10. Template Method
    Defines the skeleton of an algorithm and lets subclasses redefine certain steps.
    Example: Hook methods in frameworks like Django or React.

  11. Visitor
    Separates an algorithm from the object structure it operates on.
    Example: Operations on elements of a compiler syntax tree.


💡 Tip:

Behavioral patterns are especially useful when the flow of control is complex or when you want to change behavior at runtime without tightly coupling the classes.



Here’s a clear and concise breakdown of the Strategy and State design patterns—both of which are Behavioral Design Patterns:


🎯 Strategy Pattern

Definition:

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from the clients that use it.

🔧 When to Use:

  • You have multiple algorithms for a task (e.g., different sorting methods).

  • You want to choose the algorithm at runtime.

  • You want to avoid multiple if-else or switch-case statements for behavior changes.

🧠 Key Idea:

Behavior is defined in separate strategy classes, and the context object uses a strategy object to execute the behavior.

📦 Example:

python

class SortStrategy: def sort(self, data): pass class QuickSort(SortStrategy): def sort(self, data): print("Using QuickSort") class MergeSort(SortStrategy): def sort(self, data): print("Using MergeSort") class Context: def __init__(self, strategy: SortStrategy): self.strategy = strategy def execute_strategy(self, data): self.strategy.sort(data) context = Context(QuickSort()) context.execute_strategy([3, 1, 2]) # Output: Using QuickSort

🔄 State Pattern

Definition:

The State Pattern allows an object to change its behavior when its internal state changes. The object will appear to change its class.

🔧 When to Use:

  • An object’s behavior depends on its state.

  • You want to eliminate complex if-else or switch logic based on state.

🧠 Key Idea:

Encapsulate state-specific behavior in separate state classes and delegate state transitions to the context class.

📦 Example:

python

class State: def handle(self, context): pass class ConcreteStateA(State): def handle(self, context): print("State A → switching to State B") context.state = ConcreteStateB() class ConcreteStateB(State): def handle(self, context): print("State B → switching to State A") context.state = ConcreteStateA() class Context: def __init__(self, state: State): self.state = state def request(self): self.state.handle(self) context = Context(ConcreteStateA()) context.request() # State A → switching to State B context.request() # State B → switching to State A

🔄 Main Difference Between Strategy and State:

FeatureStrategy PatternState Pattern
PurposeSelects an algorithm at runtimeChanges behavior based on internal state
Behavior ChangeControlled externally (by user/client)Controlled internally (by the context)
Use CaseFlexible algorithm selectionDynamic behavior based on state transitions

Post a Comment

0 Comments