Member-only story
Behavioral Design Patterns: A Comprehensive Guide for Developers
Part 2: Five other behavioral patterns: Observer, State, Strategy, Template Method, and Visitor. Along with use cases and code examples.
In the previous article, we discussed five commonly used behavioral patterns: Chain of Responsibility, Command, Iterator, Mediator, and Memento. These patterns focus on creating responsibilities between objects in flexible and reusable ways.
In this article, we will discuss five other behavioral patterns: Observer, State, Strategy, Template Method, and Visitor. We will show how these patterns can be used to change object behavior, create algorithms that can be swapped out, and add new operations to existing object structures. Additionally, we will provide examples of how to use these patterns in Python.
- Introduction
- Creational Patterns
- Structural Patterns
- Behavioral Patterns (Part 1)
- Behavioral Patterns (Part 2)
Observer Pattern
The Observer pattern establishes a connection between objects, where one object is the subject and the others are observers. The subject object maintains a list of observers and automatically notifies them of any changes in its state. This promotes object independence and is commonly used in event handling and notification systems.
Use Cases
- GUI frameworks use the Observer pattern to enable UI elements to respond to changes in underlying data.
- Stock market systems use the Observer pattern to notify investors of price changes.
Code Sample — Stock Market Ticker
class StockMarket:
def __init__(self):
self.stock_price = 0.0
self.observers = []
def set_stock_price(self, price):
self.stock_price = price
self.notify_observers()
def add_observer(self, observer):
self.observers.append(observer)
def remove_observer(self, observer):
self.observers.remove(observer)
def notify_observers(self):
for observer in self.observers…