1. Home
  2. Explore
  3. Computer Science
  4. Design Patterns Introduction

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Design Patterns Introduction

Design Patterns

Design patterns are standardized solutions to common problems in software development. They provide a way to solve recurring design issues using accepted, proven approaches. Patterns improve scalability, testability, and separation of concerns, leading to better architecture. They also introduce standard terminology and best practices.

The foundational work on design patterns comes from the Gang of Four (GoF), a group of four software architects who wrote the seminal book on the subject.

Types of Design Patterns

Design patterns are classified into three main categories:

  • Creational patterns – Concerned with object creation mechanisms, trying to create objects in a manner suitable to the situation.

  • Structural patterns – Deal with object composition, focusing on how classes and objects are arranged to form larger structures.

  • Behavioral patterns – Concerned with algorithms and the assignment of responsibilities between objects, defining how objects interact and communicate.


Creational Design Patterns

Singleton Pattern

The Singleton pattern ensures that a class has only one instance and provides a single global point of access to that instance. It is useful when exactly one object is needed to coordinate actions across a system, such as a network communicator or a database connection.

Problem: Creating multiple instances of a resource-heavy component (e.g., a network communicator) wastes resources and can cause ordering or testing difficulties.

Solution: A single instance is created and shared by all components that need it. The class itself controls its instantiation.

Disadvantages:

  • Breaks the single responsibility principle – the class manages both its own state and the restriction of instantiation.

  • Testability issues – tight coupling between the singleton and its consumers makes mocking difficult.

  • Global state – once instantiated, the state persists for the application’s lifetime.

Naïve Implementation (single-threaded):

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class NetworkDriver(metaclass=Singleton):
    def log(self):
        return f"Singleton instance: {self}"

This works in single-threaded environments but fails in multithreaded ones because two threads can simultaneously check the condition and create separate instances.

Thread-Safe Implementation:

from threading import Lock

class SingletonThreadSafe(type):
    _instances = {}
    _lock = Lock()
    def __call__(cls, *args, **kwargs):
        with cls._lock:
            if cls not in cls._instances:
                cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

The lock ensures exclusive access when checking and creating the instance.

Key Takeaway:

The Singleton provides a single point of access to a shared resource, but should be used sparingly due to its drawbacks in testability and coupling.


Factory Method Pattern

The Factory Method pattern defines an interface for creating an object but lets subclasses decide which class to instantiate. It decouples the client from the actual creation logic.

Problem: Requirements change frequently, leading to code modifications. Direct instantiation ties the client to concrete classes.

Solution: A separate factory class handles object creation. The client uses a common interface to interact with objects, unaware of the concrete type.

Benefits:

  • Separation of concerns – creation logic is isolated from business logic.

  • Dynamic switching – can switch between different implementations (e.g., databases) without changing client code.

  • Extensibility – new types can be added easily.

Example (Currency Factory):

from abc import ABC, abstractmethod

class Country:
    pass

class USA(Country): pass
class Spain(Country): pass
class Japan(Country): pass

class CurrencyFactory(ABC):
    @abstractmethod
    def currency_factory(self, country: Country) -> str:
        pass

class FiatCurrencyFactory(CurrencyFactory):
    def currency_factory(self, country: Country) -> str:
        if isinstance(country, USA):
            return "USD"
        elif isinstance(country, Spain):
            return "EUR"
        elif isinstance(country, Japan):
            return "JPY"

class VirtualCurrencyFactory(CurrencyFactory):
    def currency_factory(self, country: Country) -> str:
        if isinstance(country, USA):
            return "Bitcoin"
        elif isinstance(country, Spain):
            return "Ethereum"
        elif isinstance(country, Japan):
            return "Dogecoin"

Usage:

f1 = FiatCurrencyFactory()
f2 = VirtualCurrencyFactory()
print(f1.currency_factory(USA()))   # USD
print(f2.currency_factory(Japan())) # Dogecoin

Key Takeaway:

Factory Method centralizes object creation, allowing clients to be decoupled from concrete classes and enabling easy extension.


Abstract Factory Pattern

The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is essentially a factory of factories.

Problem: Systems often need to work with multiple product families, and clients should not depend on how these families are created.

Solution: An abstract factory defines methods for creating each product type. Concrete factories implement these methods to produce products from a specific family. Clients use only the abstract factory interface.

Example (Restaurant Factory):

from enum import Enum

class FoodType(Enum):
    FRENCH = 1
    AMERICAN = 2

class Restaurant(ABC):
    @abstractmethod
    def make_food(self): pass
    @abstractmethod
    def make_drink(self): pass

class FrenchRestaurant(Restaurant):
    def make_food(self):
        print("Cordon Bleu")
    def make_drink(self):
        print("Merlot")

class AmericanRestaurant(Restaurant):
    def make_food(self):
        print("Hamburger")
    def make_drink(self):
        print("Coca-Cola")

class RestaurantFactory:
    @staticmethod
    def suggest_restaurant(restaurant_type: FoodType) -> Restaurant:
        if restaurant_type == FoodType.FRENCH:
            return FrenchRestaurant()
        else:
            return AmericanRestaurant()

def dine_at(restaurant: Restaurant):
    print("For dinner we are having:")
    restaurant.make_food()
    restaurant.make_drink()

# Usage
suggestion1 = RestaurantFactory.suggest_restaurant(FoodType.FRENCH)
suggestion2 = RestaurantFactory.suggest_restaurant(FoodType.AMERICAN)
dine_at(suggestion1)
dine_at(suggestion2)

Key Takeaway:

Abstract Factory groups related product families and ensures that clients use compatible objects without knowing concrete classes.


Builder Pattern

The Builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations.

Problem: Objects with many optional parameters lead to telescoping constructors. Using multiple constructors for every combination is impractical (e.g., 5 parameters → 120 constructors).

Solution: A builder class provides methods to set individual parameters step by step and a build() method to produce the final object. This makes the construction readable and flexible.

Classic Builder Example:

class NetworkService:
    def __init__(self):
        self.components = {}
    def add(self, key: str, value: str):
        self.components[key] = value
    def show(self):
        print(self.components)

class NetworkServiceBuilder:
    def __init__(self):
        self._service = NetworkService()
    def add_target_url(self, url: str):
        self._service.add("URL", url)
        return self
    def add_auth(self, auth: str):
        self._service.add("authorization", auth)
        return self
    def add_cache(self, cache: int):
        self._service.add("cache-control", str(cache))
        return self
    def build(self) -> NetworkService:
        service = self._service
        self._service = NetworkService()  # reset
        return service

# Usage
builder = NetworkServiceBuilder()
service1 = builder.add_target_url("google.com").build()
service2 = builder.add_target_url("youtube.com").add_auth("abc123").add_cache(60000).build()

Simplified Builder (Pythonic) using default parameters:

class NetworkService:
    def __init__(self, url: str = "", auth: str = "", cache: int = 0):
        self.components = {}
        if url:
            self.components["URL"] = url
        if auth:
            self.components["authorization"] = auth
        if cache:
            self.components["cache-control"] = str(cache)
    def show(self):
        print(self.components)

# Usage
service1 = NetworkService(url="google.com")
service2 = NetworkService(url="youtube.com", auth="abc123", cache=60000)

Key Takeaway:

The Builder pattern simplifies the construction of objects with many parameters, improving readability and flexibility.


Prototype Pattern

The Prototype pattern creates new objects by copying an existing object (the prototype) rather than instantiating from scratch. It is useful when object creation is expensive or complex.

Problem: Copying an object field by field leads to tight coupling and access issues (e.g., private fields). The copying code must know the exact class of the object.

Solution: The original object provides a copy method (e.g., clone()) that creates a duplicate, handling all internal details. In Python, the copy module provides copy() (shallow copy) and deepcopy() (deep copy).

Example:

import copy
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def draw(self): pass

class Square(Shape):
    def __init__(self, size: int):
        self.size = size
    def draw(self):
        print(f"Drawing a square of size {self.size}")

class Circle(Shape):
    def __init__(self, radius: int):
        self.radius = radius
    def draw(self):
        print(f"Drawing a circle of radius {self.radius}")

class AbstractArt:
    def __init__(self, bg_color: str, shapes: list):
        self.bg_color = bg_color
        self.shapes = shapes
    def draw(self):
        print(f"Background color is {self.bg_color}")
        for shape in self.shapes:
            shape.draw()

# Usage
shapes = [Square(5), Square(3), Circle(8)]
art1 = AbstractArt("red", shapes)
art2 = copy.copy(art1)   # shallow copy
art3 = copy.deepcopy(art1)  # deep copy

Key Takeaway:

The Prototype pattern allows copying existing objects without depending on their classes, useful for cloning complex or runtime-configured objects.


Structural Design Patterns

Adapter Pattern

The Adapter pattern converts the interface of a class into another interface that clients expect. It allows classes with incompatible interfaces to work together.

Problem: A client needs to use a third-party class or a legacy class whose interface does not match the target interface. Modifying that class is not possible or desirable.

Solution: An adapter class sits between the client and the adaptee. It translates the client's request into a form that the adaptee understands.

Example (Display data adapter):

from dataclasses import dataclass

# Third-party (adaptee)
@dataclass
class DisplayDataType:
    index: float
    data: str

class DisplayData:
    def __init__(self, display_data: DisplayDataType):
        self.display_data = display_data
    def show_data(self):
        print(f"Third-party functionality: {self.display_data.index} - {self.display_data.data}")

# Client's own data type
@dataclass
class DatabaseDataType:
    position: int
    amount: int

class StoreDatabaseData:
    def __init__(self, database_data: DatabaseDataType):
        self.database_data = database_data
    def store_data(self):
        print(f"Database data stored: {self.database_data.position} - {self.database_data.amount}")

# Adapter
class DisplayDataAdapter(StoreDatabaseData):
    def __init__(self, data: list):
        self.data = data
    def store_data(self):
        print("Adapter: using third-party code")
        for item in self.data:
            ddt = DisplayDataType(float(item.position), str(item.amount))
            self.display_data = ddt
            self.show_data()

Key Takeaway:

The Adapter pattern enables reuse of existing classes with mismatched interfaces, promoting interoperability without modifying existing code.


Bridge Pattern

The Bridge pattern decouples an abstraction from its implementation so that the two can vary independently. It avoids a proliferation of classes when there are multiple orthogonal dimensions.

Problem: For a class with two independent dimensions (e.g., shape and color), inheritance leads to an explosion of subclasses (e.g., RedCircle, BlueCircle, RedSquare, BlueSquare). Adding a new dimension multiplies the number of subclasses.

Solution: Convert inheritance into composition. Represent the two dimensions as separate class hierarchies, and connect them via a bridge – a reference from one hierarchy to the other.

Example (Device and Remote):

from abc import ABC, abstractmethod

class Device(ABC):
    def __init__(self):
        self.volume = 0
    @abstractmethod
    def get_name(self) -> str: pass

class Radio(Device):
    def get_name(self):
        return f"Radio {self}"

class TV(Device):
    def get_name(self):
        return f"TV {self}"

class Remote(ABC):
    @abstractmethod
    def volume_up(self): pass
    @abstractmethod
    def volume_down(self): pass

class BasicRemote(Remote):
    def __init__(self, device: Device):
        self.device = device
    def volume_up(self):
        self.device.volume += 1
        print(f"{self.device.get_name()} volume up: {self.device.volume}")
    def volume_down(self):
        self.device.volume -= 1
        print(f"{self.device.get_name()} volume down: {self.device.volume}")

# Usage
radio = Radio()
tv = TV()
radio_remote = BasicRemote(radio)
tv_remote = BasicRemote(tv)
radio_remote.volume_up()
tv_remote.volume_up()

Key Takeaway:

Bridge replaces multiple inheritance with composition, allowing independent changes to abstractions and implementations.


Composite Pattern

The Composite pattern composes objects into tree structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions uniformly.

Problem: A system needs to work with both simple and composite objects (e.g., pricing a computer that consists of components, which themselves may contain subcomponents). Without a common interface, handling them differently complicates code.

Solution: Both leaf (simple) and composite objects implement the same interface. Composite objects contain child components and delegate operations to them.

Example (Equipment pricing):

class Equipment:
    def __init__(self, name: str, price: int):
        self.name = name
        self.price = price

class Composite:
    def __init__(self, name: str):
        self.name = name
        self.items = []
    def add(self, equipment: Equipment):
        self.items.append(equipment)
        return self
    @property
    def price(self):
        return sum(item.price for item in self.items)
    @price.setter
    def price(self, value):
        pass  # setter only for property

# Usage
computer = Composite("PC")
processor = Equipment("Processor", 1000)
hard_drive = Equipment("Hard Drive", 250)
memory = Composite("Memory")
rom = Equipment("ROM", 100)
ram = Equipment("RAM", 75)
memory.add(rom).add(ram)
computer.add(processor).add(hard_drive).add(memory)
print(computer.price)  # 1425

Key Takeaway:

Composite allows clients to treat individual objects and composites uniformly, simplifying operations on tree structures.


Decorator Pattern

The Decorator pattern attaches additional responsibilities to an object dynamically. It provides a flexible alternative to subclassing for extending functionality.

Problem: You want to add features to an object (e.g., a third-party class) without modifying its code or creating a large number of subclasses.

Solution: A decorator class wraps the original object and implements the same interface. It adds its own behavior before or after delegating to the wrapped object. Multiple decorators can be stacked.

Example (Coffee Machine – decorating a basic machine):

from abc import ABC, abstractmethod

class CoffeeMachine(ABC):
    @abstractmethod
    def make_small_coffee(self): pass
    @abstractmethod
    def make_large_coffee(self): pass

class BasicCoffeeMachine(CoffeeMachine):
    def make_small_coffee(self):
        print("Basic coffee machine: making small coffee")
    def make_large_coffee(self):
        print("Basic coffee machine: making large coffee")

class EnhancedCoffeeMachine(CoffeeMachine):
    def __init__(self, basic_machine: BasicCoffeeMachine):
        self.basic_machine = basic_machine
    def make_small_coffee(self):
        self.basic_machine.make_small_coffee()   # use underlying behavior
    def make_large_coffee(self):
        print("Enhanced coffee machine: making large coffee")  # overridden
    def make_milk_coffee(self):
        print("Enhanced coffee machine: making milk coffee")
        self.basic_machine.make_small_coffee()
        print("Enhanced coffee machine: adding milk")

# Usage
basic = BasicCoffeeMachine()
enhanced = EnhancedCoffeeMachine(basic)
enhanced.make_small_coffee()
enhanced.make_large_coffee()
enhanced.make_milk_coffee()

Key Takeaway:

Decorator provides a flexible way to extend object functionality without altering the original class, following the open/closed principle.


Facade Pattern

The Facade pattern provides a simplified, unified interface to a set of interfaces in a subsystem. It hides the complexity of the subsystem from the client.

Problem: A client may need to interact with a complex system (e.g., multiple classes with intricate dependencies). Direct usage leads to tight coupling and a steep learning curve.

Solution: A facade class offers a simple, high-level interface. It delegates client requests to the appropriate subsystem components, managing underlying complexities.

Example (User storage with a storage facade):

from dataclasses import dataclass

class ComplexSystemStore:
    def __init__(self, file_path: str):
        self.file_path = file_path
        self.cache = {}
        print(f"Reading data from file: {file_path}")
    def store(self, key: str, value: str):
        self.cache[key] = value
    def read(self, key: str) -> str:
        return self.cache.get(key, "")
    def commit(self):
        print(f"Storing cached data to file: {self.file_path}")

@dataclass
class User:
    login: str

class UserRepository:
    def __init__(self):
        self.system_preferences = ComplexSystemStore("data/default.prefs")
    def save(self, user: User):
        self.system_preferences.store("USER_KEY", user.login)
        self.system_preferences.commit()
    def find_first(self) -> User:
        login = self.system_preferences.read("USER_KEY")
        return User(login)

# Usage
repo = UserRepository()
repo.save(User("John"))
retrieved = repo.find_first()
print(retrieved.login)  # John

Key Takeaway:

Facade simplifies client interaction with complex subsystems, promoting loose coupling and easier maintenance.


Flyweight Pattern

The Flyweight pattern reduces memory usage by sharing as much data as possible with other similar objects. It is particularly effective when a large number of objects are created that share common state.

Problem: In systems with many similar objects (e.g., characters in a game, Sprites), creating a unique object for each instance consumes excessive memory.

Solution: Separate intrinsic state (shared, immutable) from extrinsic state (context-dependent). Intrinsic state is stored in a shared flyweight object. A factory manages flyweights and returns existing ones when possible.

Example (Army of Fighters):

import random
from enum import Enum

class FighterRank(Enum):
    PRIVATE = 0
    SERGEANT = 1
    MAJOR = 2

class Sprite(ABC):
    @abstractmethod
    def draw(self): pass
    @abstractmethod
    def move(self, x: int, y: int): pass

class Fighter(Sprite):
    def __init__(self, rank: FighterRank):
        self.rank = rank
    def draw(self):
        print(f"Drawing fighter {self}")
    def move(self, x: int, y: int):
        print(f"Moving fighter {self} to ({x}, {y})")

class FighterFactory:
    def __init__(self):
        self._fighters = {}
    def get_fighter(self, rank: FighterRank) -> Fighter:
        fighter = self._fighters.get(rank)
        if not fighter:
            fighter = Fighter(rank)
            self._fighters[rank] = fighter
        return fighter

class Army:
    def __init__(self):
        self._army = []
    def spawn_fighter(self, rank: FighterRank):
        self._army.append(fighter_factory.get_fighter(rank))
    def draw_army(self):
        for fighter in self._army:
            if fighter.rank == FighterRank.MAJOR:
                print("M", end="")
            elif fighter.rank == FighterRank.SERGEANT:
                print("S", end="")
            else:
                print("P", end="")
        print()

# Usage
fighter_factory = FighterFactory()
army = Army()
for _ in range(1000):
    rank = random.choice(list(FighterRank))
    army.spawn_fighter(rank)
army.draw_army()

Key Takeaway:

Flyweight reduces memory footprint by sharing intrinsic state across many objects, crucial for systems with large numbers of similar objects.


Proxy Pattern

The Proxy pattern provides a surrogate or placeholder for another object to control access to it. The proxy has the same interface as the real object.

Problem: Direct access to an object may be inefficient (e.g., loading large images), requires additional controls (e.g., access rights), or is costly. You want to add a layer of indirection.

Solution: A proxy class implements the same interface as the real subject. It performs additional logic (e.g., caching, lazy loading, access control) before forwarding requests to the real subject.

Key distinction:

  • Proxy: Manages the lifecycle of the real object; provides the same interface.

  • Facade: Provides a simplified interface to a complex subsystem.

  • Decorator: Adds behavior; the client may not be aware of the wrapper.

Example (Image proxy with caching):

from abc import ABC, abstractmethod

class Image(ABC):
    @abstractmethod
    def display(self): pass

class RealImage(Image):
    def __init__(self, filename: str):
        self.filename = filename
        print(f"Real image loading: {filename}")
    def display(self):
        print(f"Real image displaying: {self.filename}")

class ProxyImage(Image):
    def __init__(self, filename: str):
        self.filename = filename
        self._real_image = None
    def display(self):
        print(f"Proxy image displaying: {self.filename}")
        if not self._real_image:
            print("Loading from disk")
            self._real_image = RealImage(self.filename)
        else:
            print("Loading from cache")
        self._real_image.display()

# Usage
image = ProxyImage("test.jpeg")
image.display()   # loads from disk
print("---")
image.display()   # loads from cache

Key Takeaway:

Proxy controls and manages access to an object, adding a layer of indirection that can improve performance, security, or lazy initialization.


Behavioral Design Patterns

Chain of Responsibility Pattern

The Chain of Responsibility pattern allows multiple objects to handle a request by chaining them. Each handler either processes the request or passes it to the next handler in the chain.

Problem: A request may need to be processed by one of several handlers, but the exact handler is not known beforehand. Hard-coding the decision logic leads to tight coupling.

Solution: Create a chain of handler objects. Each handler holds a reference to the next handler. The request starts at the first handler and travels along the chain until a handler consumes it.

Example (HTTP header adding chain):

from __future__ import annotations
from abc import ABC, abstractmethod

class HandlerChain(ABC):
    def __init__(self, next_header: HandlerChain = None):
        self.next_header = next_header
    @abstractmethod
    def add_header(self, input_header: str) -> str: pass
    def do_next(self, input_header: str) -> str:
        if self.next_header:
            return self.next_header.add_header(input_header)
        return input_header

class AuthenticationHeader(HandlerChain):
    def __init__(self, token: str, next_header: HandlerChain = None):
        super().__init__(next_header)
        self.token = token
    def add_header(self, input_header: str) -> str:
        h = input_header + f"\nAuthorization: {self.token}"
        return self.do_next(h)

class ContentTypeHeader(HandlerChain):
    def __init__(self, content_type: str, next_header: HandlerChain = None):
        super().__init__(next_header)
        self.content_type = content_type
    def add_header(self, input_header: str) -> str:
        h = input_header + f"\nContent-Type: {self.content_type}"
        return self.do_next(h)

class BodyPayloadHeader(HandlerChain):
    def __init__(self, body: str, next_header: HandlerChain = None):
        super().__init__(next_header)
        self.body = body
    def add_header(self, input_header: str) -> str:
        h = input_header + f"\n{self.body}"
        return self.do_next(h)

# Usage
auth = AuthenticationHeader("123456")
content_type = ContentTypeHeader("json")
body = BodyPayloadHeader('{"username":"John"}')
auth.next_header = content_type
content_type.next_header = body

message_with_auth = auth.add_header("Header with authentication")
print(message_with_auth)
print("---")
message_without_auth = content_type.add_header("Header without authentication")
print(message_without_auth)

Key Takeaway:

Chain of Responsibility decouples senders and receivers by giving multiple objects a chance to handle a request.


Command Pattern

The Command pattern encapsulates a request as an object, thereby allowing parameterization of clients with queues, requests, and operations. It supports undoable operations.

Problem: Direct invocation of methods couples the sender to the receiver and makes it hard to queue, log, or undo operations.

Solution: Each operation is turned into a command object with an execute() method. An invoker (e.g., a processor) stores commands and calls execute() at a later time.

Example (Order system):

from abc import ABC, abstractmethod

class Command(ABC):
    def __init__(self, command_id: int):
        self.command_id = command_id
    @abstractmethod
    def execute(self): pass

class OrderAddCommand(Command):
    def execute(self):
        print(f"Adding order with ID {self.command_id}")

class OrderPayCommand(Command):
    def execute(self):
        print(f"Paying for order with ID {self.command_id}")

class CommandProcessor:
    def __init__(self):
        self.queue = []
    def add_to_queue(self, command: Command):
        self.queue.append(command)
    def process_commands(self):
        for item in self.queue:
            item.execute()
        self.queue.clear()

# Usage
processor = CommandProcessor()
processor.add_to_queue(OrderAddCommand(1))
processor.add_to_queue(OrderAddCommand(2))
processor.add_to_queue(OrderPayCommand(1))
processor.add_to_queue(OrderPayCommand(2))
processor.process_commands()

Key Takeaway:

The Command pattern decouples action invocation from execution, enabling queuing, logging, and undo support.


Interpreter Pattern

The Interpreter pattern defines a grammatical representation for a language and an interpreter that uses the representation to interpret sentences in the language.

Problem: You need to parse and evaluate expressions in a simple language (e.g., arithmetic, configuration files). Building a full parser is overkill.

Solution: Represent each grammar rule as a class. Terminal expressions represent basic elements (like numbers), and non-terminal expressions represent grammar rules (like addition). The interpreter recursively evaluates the expression tree.

Example (Arithmetic expression interpreter):

class AbstractExpression:
    @staticmethod
    def interpret(): pass

class NumberExpression(AbstractExpression):
    def __init__(self, value):
        self.value = float(value)
    def interpret(self):
        return self.value

class AlgebraExpression(AbstractExpression):
    def __init__(self, left, right):
        self.left = left
        self.right = right

class AddExpression(AlgebraExpression):
    def interpret(self):
        return self.left.interpret() + self.right.interpret()

class SubtractExpression(AlgebraExpression):
    def interpret(self):
        return self.left.interpret() - self.right.interpret()

class MultiplyExpression(AlgebraExpression):
    def interpret(self):
        return self.left.interpret() * self.right.interpret()

class DivideExpression(AlgebraExpression):
    def interpret(self):
        return self.left.interpret() / self.right.interpret()

# Usage
target = "3 + 5 - 2 * 7 / 5 + 11"
tokens = target.split()
expressions = []
for i, token in enumerate(tokens):
    if i == 0 or token in ('*', '/'):
        if token in ('*', '/'):
            right = NumberExpression(tokens[i+1])
            left = expressions.pop()
            expr = MultiplyExpression(left, right) if token == '*' else DivideExpression(left, right)
            expressions.append(expr)
        else:
            expressions.append(NumberExpression(token))
    elif token in ('+', '-'):
        right = NumberExpression(tokens[i+1])
        left = expressions.pop()
        expr = AddExpression(left, right) if token == '+' else SubtractExpression(left, right)
        expressions.append(expr)
result = expressions.pop().interpret()
print(result)  # 19.4

Key Takeaway:

Interpreter is useful for implementing simple language interpreters, enabling evaluation of expressions defined by a grammar.


Iterator Pattern

The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Problem: Different collections (arrays, lists, trees) may require different traversal algorithms. Exposing these internals couples clients to the collection's structure.

Solution: Define an iterator interface with methods like has_next() and next(). Each collection provides iterators that know how to traverse itself.

Example (Alphabetical order iterator):

class AlphabeticalOrderIterator:
    def __init__(self, words: list, reverse: bool = False):
        self.collection = sorted(words)
        self.reverse = reverse
        self.position = len(words) - 1 if reverse else 0
    def next(self):
        value = self.collection[self.position]
        self.position += -1 if self.reverse else 1
        return value
    def has_next(self) -> bool:
        if self.reverse:
            return self.position >= 0
        else:
            return self.position < len(self.collection)

class WordsCollection:
    def __init__(self, collection: list):
        self.collection = collection
    def get_iterator(self):
        return AlphabeticalOrderIterator(self.collection, False)
    def get_reverse_iterator(self):
        return AlphabeticalOrderIterator(self.collection, True)

# Usage
collection = WordsCollection(["John", "Alice", "Michael", "Carol"])
iterator = collection.get_iterator()
while iterator.has_next():
    print(iterator.next())
print("---")
reverse_iterator = collection.get_reverse_iterator()
while reverse_iterator.has_next():
    print(reverse_iterator.next())

Key Takeaway:

Iterator provides a uniform way to traverse collections, hiding the implementation details and supporting multiple traversal types.


Mediator Pattern

The Mediator pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly.

Problem: In a system with many interacting components (e.g., chat users, microservices), direct communication creates a web of dependencies that is hard to maintain.

Solution: A mediator object centralizes communication. Components send messages only to the mediator, which forwards them to the appropriate recipients.

Example (Chat system):

from __future__ import annotations

class ChatUser:
    def __init__(self, name: str):
        self.name = name
        self.mediator = None
    def set_mediator(self, mediator: Mediator):
        self.mediator = mediator
    def send(self, msg: str):
        print(f"{self.name}: sending message {msg}")
        self.mediator.send_message(msg, self)
    def receive(self, msg: str):
        print(f"{self.name}: receiving message {msg}")

class Mediator:
    def __init__(self):
        self.users = []
    def add_user(self, user: ChatUser):
        self.users.append(user)
        user.set_mediator(self)
    def send_message(self, msg: str, sender: ChatUser):
        for user in self.users:
            if user != sender:
                user.receive(msg)

# Usage
mediator = Mediator()
alice = ChatUser("Alice")
bob = ChatUser("Bob")
carol = ChatUser("Carol")
mediator.add_user(alice)
mediator.add_user(bob)
mediator.add_user(carol)
carol.send("Hi everyone")

Key Takeaway:

Mediator reduces coupling between components by acting as a central hub for communication, improving maintainability.


Memento Pattern

The Memento pattern captures and externalizes an object's internal state so that the object can be restored to this state later, without violating encapsulation.

Problem: You need to implement undo/redo functionality, but direct exposure of internal state breaks encapsulation.

Solution: The originator (object whose state is saved) creates a memento object containing a snapshot of its state. A caretaker stores mementos and can restore the originator to a previous state.

Example (Undo system):

from dataclasses import dataclass

@dataclass
class Memento:
    state: str

class Originator:
    def __init__(self, state: str):
        self.state = state
    def create_memento(self) -> Memento:
        return Memento(self.state)
    def restore_memento(self, memento: Memento):
        self.state = memento.state

class Caretaker:
    def __init__(self):
        self.memento_list = []
    def save_state(self, memento: Memento):
        self.memento_list.append(memento)
    def restore(self, index: int) -> Memento:
        return self.memento_list[index]

# Usage
originator = Originator("Initial State")
caretaker = Caretaker()
caretaker.save_state(originator.create_memento())
print(f"Current state: {originator.state}")  # Initial

originator.state = "State 1"
caretaker.save_state(originator.create_memento())
print(f"Current state: {originator.state}")  # State 1

originator.state = "State 2"
caretaker.save_state(originator.create_memento())
print(f"Current state: {originator.state}")  # State 2

originator.restore_memento(caretaker.restore(1))
print(f"Restored to: {originator.state}")    # State 1

originator.restore_memento(caretaker.restore(0))
print(f"Restored to: {originator.state}")    # Initial

Key Takeaway:

Memento enables undo/redo functionality without exposing internal object details, maintaining encapsulation.


Observer Pattern

The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Problem: When a subject (e.g., a data source) changes, multiple dependent objects need to be updated. Polling for changes is inefficient and wasteful.

Solution: The subject maintains a list of observers (subscribers). Observers register their interest. When the subject's state changes, it iterates over the list and notifies each observer.

Example (Event notification system):

from abc import ABC, abstractmethod

class EventListener(ABC):
    @abstractmethod
    def update(self, event_type: str, file: str): pass

class EventManager:
    def __init__(self, operations: list):
        self.operations = operations
        self.listeners = {op: [] for op in operations}
    def subscribe(self, event_type: str, listener: EventListener):
        self.listeners[event_type].append(listener)
    def unsubscribe(self, event_type: str, listener: EventListener):
        self.listeners[event_type].remove(listener)
    def notify(self, event_type: str, file: str):
        for listener in self.listeners[event_type]:
            listener.update(event_type, file)

class Editor:
    def __init__(self):
        self.events = EventManager(["open", "save"])
        self.file = None
    def open_file(self, file: str):
        self.file = file
        print(f"Editor: opening file {file}")
        self.events.notify("open", file)
    def save_file(self):
        print(f"Editor: saving file {self.file}")
        self.events.notify("save", self.file)

class EmailNotificationListener(EventListener):
    def __init__(self, email: str):
        self.email = email
    def update(self, event_type: str, file: str):
        print(f"Email to {self.email}: Someone performed {event_type} on {file}")

class LogOpenListener(EventListener):
    def __init__(self, log_file: str):
        self.log_file = log_file
    def update(self, event_type: str, file: str):
        print(f"Save to log {self.log_file}: Someone performed {event_type} on {file}")

# Usage
editor = Editor()
email_listener = EmailNotificationListener("test@gmail.com")
log_listener = LogOpenListener("path/to/log.txt")
editor.events.subscribe("open", log_listener)
editor.events.subscribe("save", log_listener)
editor.events.subscribe("save", email_listener)
editor.open_file("test.txt")
editor.save_file()

Key Takeaway:

Observer decouples subjects from observers, enabling efficient event-driven updates without polling.


State Pattern

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

Problem: An object's behavior depends on its state, and the number of states is finite. Implementing state-specific logic in conditional statements (if/else) makes the code complex and hard to maintain.

Solution: Each state is represented as a separate class that implements a common interface. The context object (e.g., a game) holds a reference to the current state object and delegates state-specific behavior to it.

Example (Game state machine):

from __future__ import annotations
from abc import ABC, abstractmethod
import random

class Game:
    def __init__(self):
        self.state = WelcomeScreenState(self)
    def change_state(self, state: State):
        self.state = state

class State(ABC):
    def __init__(self, game: Game):
        self.game = game
    @abstractmethod
    def on_welcome_screen(self): pass
    @abstractmethod
    def on_playing(self): pass
    @abstractmethod
    def on_break(self): pass
    @abstractmethod
    def on_end_game(self): pass

class WelcomeScreenState(State):
    def on_welcome_screen(self):
        print("Currently on welcome screen")
    def on_playing(self):
        print("Moving from welcome to playing")
        self.game.change_state(PlayingState(self.game))
    def on_break(self):
        print("From welcome to break not allowed")
    def on_end_game(self):
        print("From welcome to end game not allowed")

class PlayingState(State):
    def on_welcome_screen(self):
        print("From playing to welcome not allowed")
    def on_playing(self):
        print("Currently playing")
    def on_break(self):
        print("Moving from playing to break")
        self.game.change_state(BreakState(self.game))
    def on_end_game(self):
        print("Moving from playing to end game")
        self.game.change_state(EndGameState(self.game))

class BreakState(State):
    def on_welcome_screen(self):
        print("From break to welcome not allowed")
    def on_playing(self):
        print("Moving from break to playing")
        self.game.change_state(PlayingState(self.game))
    def on_break(self):
        print("Currently on break")
    def on_end_game(self):
        print("From break to end game not allowed")

class EndGameState(State):
    def on_welcome_screen(self):
        print("Moving from end game to welcome")
        self.game.change_state(WelcomeScreenState(self.game))
    def on_playing(self):
        print("From end game to playing not allowed")
    def on_break(self):
        print("From end game to break not allowed")
    def on_end_game(self):
        print("Currently on end game")

# Usage
game = Game()
for _ in range(20):
    state = random.randint(0,3)
    if state == 0:
        print("Move to welcome")
        game.state.on_welcome_screen()
    elif state == 1:
        print("Move to playing")
        game.state.on_playing()
    elif state == 2:
        print("Move to break")
        game.state.on_break()
    else:
        print("Move to end game")
        game.state.on_end_game()

Key Takeaway:

The State pattern encapsulates state-specific behavior in separate classes, making transitions explicit and simplifying context code.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent