Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

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.

Oleh Davymuka
Python in Plain English
10 min readJul 2, 2023

--

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.

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

  1. GUI frameworks use the Observer pattern to enable UI elements to respond to changes in underlying data.
  2. 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…

--

--

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

No responses yet

Write a response