Richard Qiu

Design Patterns

3 notes

Contents

Design Principles (SOLID)

S - Single Responsibility Principle (SRP)

A class should have one and only one reason to change. Each class should do one thing only.

class Journal:
    def __init__(self):
        self.entries = []
        self.count = 0

    def add_entry(self, text):
        self.entries.append(f"{self.count}: {text}")
        self.count += 1

    def remove_entry(self, pos):
        del self.entries[pos]

    def __str__(self):
        return "\n".join(self.entries)

    # break SRP
    def save(self, filename):
        file = open(filename, "w")
        file.write(str(self))
        file.close()

    def load(self, filename):
        pass

    def load_from_web(self, uri):
        pass


class PersistenceManager:
    def save_to_file(journal, filename):
        file = open(filename, "w")
        file.write(str(journal))
        file.close()


j = Journal()
j.add_entry("I cried today.")
j.add_entry("I ate a bug.")
print(f"Journal entries:\n{j}\n")

p = PersistenceManager()
file = r'c:\temp\journal.txt'
p.save_to_file(j, file)

# verify!
with open(file) as fh:
    print(fh.read())

O - Open/Closed Principle (OCP)

Software entities should be open for extension, but closed for modification. New behavior should be added via extension rather than altering existing code.

Benefits:

  • Avoids touching stable, tested code
  • Reduces the risk of introducing bugs when adding features
  • Encourages use of polymorphism, abstraction, and inheritance or composition

Problem Example (Violates OCP). Here, every time you add a new shape type, you must modify AreaCalculator, violating OCP.

class Shape:
    def __init__(self, type):
        self.type = type

class AreaCalculator:
    def calculate(self, shapes):
        for shape in shapes:
            if shape.type == 'circle':
                # calculate circle area
            elif shape.type == 'square':
                # calculate square area

OCP-Compliant Example (Using Polymorphism)

from abc import ABC, abstractmethod

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

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

class AreaCalculator:
    def calculate(self, shapes):
        return sum(shape.area() for shape in shapes)

When to Apply

  • When a module is stable but requires new features

  • When you want to reduce the impact of future changes

  • In plugin architectures, rule engines, or strategy-based designs

    from enum import Enum
    
    
    class Color(Enum):
        RED = 1
        GREEN = 2
        BLUE = 3
    
    
    class Size(Enum):
        SMALL = 1
        MEDIUM = 2
        LARGE = 3
    
    
    class Product:
        def __init__(self, name, color, size):
            self.name = name
            self.color = color
            self.size = size
    
    
    class ProductFilter:
        def filter_by_color(self, products, color):
            for p in products:
                if p.color == color:
                    yield p
    
        def filter_by_size(self, products, size):
            for p in products:
                if p.size == size:
                    yield p
    
        def filter_by_size_and_color(self, products, size, color):
            for p in products:
                if p.color == color and p.size == size:
                    yield p
    
        # state space explosion
        # 3 criteria
        # c s w cs sw cw csw = 7 methods
    
        # OCP = open for extension, closed for modification
    
    
    class Specification:
        def is_satisfied(self, item):
            pass
    
        # and operator makes life easier
        def __and__(self, other):
            return AndSpecification(self, other)
    
    
    class Filter:
        def filter(self, items, spec):
            pass
    
    
    class ColorSpecification(Specification):
        def __init__(self, color):
            self.color = color
    
        def is_satisfied(self, item):
            return item.color == self.color
    
    
    class SizeSpecification(Specification):
        def __init__(self, size):
            self.size = size
    
        def is_satisfied(self, item):
            return item.size == self.size
    
    
    # class AndSpecification(Specification):
    #     def __init__(self, spec1, spec2):
    #         self.spec2 = spec2
    #         self.spec1 = spec1
    #
    #     def is_satisfied(self, item):
    #         return self.spec1.is_satisfied(item) and \
    #                self.spec2.is_satisfied(item)
    
    
    class AndSpecification(Specification):
        def __init__(self, *args):
            self.args = args
    
        def is_satisfied(self, item):
            return all(map(lambda spec: spec.is_satisfied(item), self.args))
    
    
    class BetterFilter(Filter):
        def filter(self, items, spec):
            for item in items:
                if spec.is_satisfied(item):
                    yield item
    
    
    apple = Product("Apple", Color.GREEN, Size.SMALL)
    tree = Product("Tree", Color.GREEN, Size.LARGE)
    house = Product("House", Color.BLUE, Size.LARGE)
    
    products = [apple, tree, house]
    
    pf = ProductFilter()
    print("Green products (old):")
    for p in pf.filter_by_color(products, Color.GREEN):
        print(f" - {p.name} is green")
    
    # ^ BEFORE
    
    # v AFTER
    bf = BetterFilter()
    
    print("Green products (new):")
    green = ColorSpecification(Color.GREEN)
    for p in bf.filter(products, green):
        print(f" - {p.name} is green")
    
    print("Large products:")
    large = SizeSpecification(Size.LARGE)
    for p in bf.filter(products, large):
        print(f" - {p.name} is large")
    
    print("Large blue items:")
    # large_blue = AndSpecification(large, ColorSpecification(Color.BLUE))
    large_blue = large & ColorSpecification(Color.BLUE)
    for p in bf.filter(products, large_blue):
        print(f" - {p.name} is large and blue")

L - Liskov Substitution Principle (LSP)

I - Interface Segregation Principle (ISP)

D - Dependency Inversion Principle (DIP)

Structural Patterns

Proxy

Proxy

The Proxy pattern provides a placeholder or surrogate for another object to control access to it. It allows additional behavior (e.g., access control, logging, or lazy loading) while keeping the client interface unchanged.

Motivation

In distributed or modular systems, an object like Foo may be relocated to a different process or environment over time. Instead of rewriting all code that interacts with Foo, a proxy class can maintain the same interface while handling the new complexity (e.g., inter-process communication, remote calls).

A **proxy **Structure:

  • Implements the same interface as the target object.
  • Delegates requests to the real object (optionally adding behavior before or after the call).

Common Use Cases

  • Remote Proxy (Communication Proxy): Manages communication with an object in a different address space or process.
  • Virtual Proxy: Delays the creation of an expensive object until it’s needed.
  • Logging Proxy: Logs method calls and arguments.
  • Protection (Guard) Proxy: Controls access based on authorization.

Protection Proxy

Use for access control.

class Car:
    def __init__(self, driver):
        self.driver = driver

    def drive(self):
        print(f'Car being driven by {self.driver.name}')

class CarProxy:
    def __init__(self, driver):
        self.driver = driver
        self.car = Car(driver)

    def drive(self):
        if self.driver.age >= 16:
            self.car.drive()
        else:
            print('Driver too young')


class Driver:
    def __init__(self, name, age):
        self.name = name
        self.age = age


if __name__ == '__main__':
    car = CarProxy(Driver('John', 12))
    car.drive()

Virtual Proxy

The issue is if we initiate the Bitmap object but not drawing the image, it will call the init function which will load image from filename. And also by adding the virtual proxy, it ensures the real object is constructed only on first use, making systems more efficient without changing the public interface.

class Bitmap:
    def __init__(self, filename):
        self.filename = filename
        print(f'Loading image from {filename}')

    def draw(self):
        print(f'Drawing image {self.filename}')


class LazyBitmap:
    def __init__(self, filename):
        self.filename = filename
        self.bitmap = None

    def draw(self):
        if not self.bitmap:
            self.bitmap = Bitmap(self.filename)
        self.bitmap.draw()

def draw_image(image):
    print('About to draw image')
    image.draw()
    print('Done drawing image')

if __name__ == '__main__':
    bmp = LazyBitmap('facepalm.jpg')  # Bitmap
    draw_image(bmp)

Proxy vs Decorator

Both Proxy and Decorator patterns involve an object wrapping another, but they serve different design goals. Below is a structured comparison to clarify their purposes and behaviors.

  • Proxy: Controls access to an object. It may:
    • Delay creation (lazy loading)
    • Add logging, security checks, or communication boundaries
    • Operate before the real object exists
  • Decorator: Adds functionality around an existing object. It enhances behavior without altering the object’s core structure.

Think of Proxy as a transparent stand-in that may control object creation, and Decorator as a behavior enhancer that wraps and extends functionality.

Exercise

from unittest import TestCase


class Person:
  def __init__(self, age):
    self.age = age

  def drink(self):
    return 'drinking'

  def drive(self):
    return 'driving'

  def drink_and_drive(self):
    return 'driving while drunk'

class ResponsiblePerson:
  def __init__(self, person):
    self.person = person

  @property
  def age(self):
    return self.person.age

  @age.setter
  def age(self, value):
    self.person.age = value

  def drink(self):
    if self.age >= 18:
      return self.person.drink()
    return 'too young'

  def drive(self):
    if self.age >= 16:
      return self.person.drive()
    return 'too young'

  def drink_and_drive(self):
    return 'dead'

class Evaluate(TestCase):
  def test_exercise(self):
    p = Person(10)
    rp = ResponsiblePerson(p)

    self.assertEqual('too young', rp.drive())
    self.assertEqual('too young', rp.drink())
    self.assertEqual('dead', rp.drink_and_drive())

    rp.age = 20

    self.assertEqual('driving', rp.drive())
    self.assertEqual('drinking', rp.drink())
    self.assertEqual('dead', rp.drink_and_drive())

Summary

The Proxy Pattern is a structural design pattern that acts as a stand-in or interface to control access to another object. It maintains the same interface as the original object, allowing clients to interact with the proxy transparently while adding additional behavior like access control, logging, or lazy instantiation.

Key proxy types include:

  • Virtual Proxy – Delays expensive object creation until first use.
  • Protection Proxy – Restricts access based on permissions or conditions.
  • Remote Proxy – Handles interaction across different processes or machines.
  • Logging Proxy – Adds logging or auditing behavior around method calls.

Proxy is often compared to the Decorator Pattern, but unlike decorators, proxies are used to control access or defer operations, not just enhance behavior. Decorators always work with an existing object, whereas proxies may create or represent an object lazily.

Use the Proxy pattern when:

  • The real object is expensive or unnecessary to initialize upfront
  • Access to the object needs to be controlled or monitored
  • Remote access or security checks are involved

Structural Patterns

Chain of Responsibility

Chain of Responsibility

The Chain of Responsibility pattern allows multiple objects the chance to handle a request without the sender needing to know which one will handle it. The request is passed along a chain until an object handles it or the chain ends.

Motivation

In real-world scenarios, responsibilities often flow up a hierarchy. For example, in a company, if an employee behaves unethically, the blame may fall on the employee, their manager, or even the CEO—depending on the severity and source of the behavior. This layered delegation is an example of a chain of responsibility.

Similarly, in UI applications, when a user clicks a button, the button may handle the event. If it doesn’t, the event bubbles up to the parent component (like a group box), and then possibly to the window itself. Each element in the hierarchy gets a chance to handle the event.

Another example is a card game where a creature’s stats (like attack and defense) can be modified by multiple other cards. Each modifier can be seen as a handler in the chain that alters the request.

In all these cases, the idea is to:

  • Pass a request through a chain of handlers
  • Let each handler decide to process or forward it
  • Allow optional early termination of the chain

This pattern is ideal for building flexible, decoupled systems where multiple parties might act on a single input.

Method Chain

class Creature:
    def __init__(self, name, attack, defense):
        self.defense = defense
        self.attack = attack
        self.name = name

    def __str__(self):
        return f'{self.name} ({self.attack}/{self.defense})'


class CreatureModifier:
    def __init__(self, creature):
        self.creature = creature
        self.next_modifier = None

    def add_modifier(self, modifier):
        if self.next_modifier:
            self.next_modifier.add_modifier(modifier)
        else:
            self.next_modifier = modifier

    def handle(self):
        if self.next_modifier:
            self.next_modifier.handle()


class NoBonusesModifier(CreatureModifier):
    def handle(self):
        print('No bonuses for you!')


class DoubleAttackModifier(CreatureModifier):
    def handle(self): # in Python, if no init called, the init will get inherited automatically
        print(f'Doubling {self.creature.name}''s attack')
        self.creature.attack *= 2
        super().handle()


class IncreaseDefenseModifier(CreatureModifier):
    def handle(self):
        if self.creature.attack <= 2:
            print(f'Increasing {self.creature.name}''s defense')
            self.creature.defense += 1
        super().handle()


if __name__ == '__main__':
    goblin = Creature('Goblin', 1, 1)
    print(goblin)

    root = CreatureModifier(goblin)

    root.add_modifier(NoBonusesModifier(goblin))

    root.add_modifier(DoubleAttackModifier(goblin))
    root.add_modifier(DoubleAttackModifier(goblin))

    # no effect
    root.add_modifier(IncreaseDefenseModifier(goblin))

    root.handle()  # apply modifiers
    print(goblin)

Command Query Separation

  • Command = asking for an action or change (e.g., please set your attack value to 2).
  • Query = asking for information (e.g., please give me your attack value).
  • CQS = having separate means of sending commands and queries to e.g., direct field access.

Broker Chain

# 1) event broker
# 2) command-query separation (cqs)
# 3) observer
from abc import ABC
from enum import Enum


class Event(list):
    def __call__(self, *args, **kwargs):
        for item in self:
            item(*args, **kwargs)


class WhatToQuery(Enum):
    ATTACK = 1
    DEFENSE = 2


class Query:
    def __init__(self, creature_name, what_to_query, default_value):
        self.value = default_value  # bidirectional
        self.what_to_query = what_to_query
        self.creature_name = creature_name


class Game:
    def __init__(self):
        self.queries = Event()

    def perform_query(self, sender, query):
        self.queries(sender, query)


class Creature:
    def __init__(self, game, name, attack, defense):
        self.initial_defense = defense
        self.initial_attack = attack
        self.name = name
        self.game = game

    @property
    def attack(self):
        q = Query(self.name, WhatToQuery.ATTACK, self.initial_attack)
        self.game.perform_query(self, q)
        return q.value

    @property
    def defense(self):
        q = Query(self.name, WhatToQuery.DEFENSE, self.initial_attack)
        self.game.perform_query(self, q)
        return q.value

    def __str__(self):
        return f'{self.name} ({self.attack}/{self.defense})'


class CreatureModifier(ABC):
    def __init__(self, game, creature):
        self.creature = creature
        self.game = game
        self.game.queries.append(self.handle)

    def handle(self, sender, query):
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.game.queries.remove(self.handle)


class DoubleAttackModifier(CreatureModifier):
    def handle(self, sender, query):
        if (sender.name == self.creature.name and
                query.what_to_query == WhatToQuery.ATTACK):
            query.value *= 2


class IncreaseDefenseModifier(CreatureModifier):
    def handle(self, sender, query):
        if (sender.name == self.creature.name and
                query.what_to_query == WhatToQuery.DEFENSE):
            query.value += 3


if __name__ == '__main__':
    game = Game()
    goblin = Creature(game, 'Strong Goblin', 2, 2)
    print(goblin)

    with DoubleAttackModifier(game, goblin):
        print(goblin)
        with IncreaseDefenseModifier(game, goblin):
            print(goblin)

    print(goblin)

Exercise

import unittest
from abc import ABC
from enum import Enum

# creature removal (unsubscription) ignored in this exercise solution

class Creature(ABC):
    def __init__(self, game, attack, defense):
        self.initial_defense = defense
        self.initial_attack = attack
        self.game = game

    @property
    def attack(self): pass

    @property
    def defense(self): pass

    def query(self, source, query): pass


class WhatToQuery(Enum):
    ATTACK = 1
    DEFENSE = 2


class Goblin(Creature):

    def __init__(self, game, attack=1, defense=1):
        super().__init__(game, attack, defense)

    @property
    def attack(self):
        q = Query(self.initial_attack, WhatToQuery.ATTACK)
        for c in self.game.creatures:
            c.query(self, q)
        return q.value

    @property
    def defense(self):
        q = Query(self.initial_defense, WhatToQuery.DEFENSE)
        for c in self.game.creatures:
            c.query(self, q)
        return q.value

    def query(self, source, query):
        if self != source and query.what_to_query == WhatToQuery.DEFENSE:
            query.value += 1


class GoblinKing(Goblin):

    def __init__(self, game):
        super().__init__(game, 3, 3)

    def query(self, source, query):
        if self != source and query.what_to_query == WhatToQuery.ATTACK:
            query.value += 1
        else:
            super().query(source, query)


class Query:
    def __init__(self, initial_value, what_to_query):
        self.what_to_query = what_to_query
        self.value = initial_value

class Game:
    def __init__(self):
        self.creatures = []


class FirstTestSuite(unittest.TestCase):
    def test(self):
        game = Game()
        goblin = Goblin(game)
        game.creatures.append(goblin)

        self.assertEqual(1, goblin.attack)
        self.assertEqual(1, goblin.defense)

        goblin2 = Goblin(game)
        game.creatures.append(goblin2)

        self.assertEqual(1, goblin.attack)
        self.assertEqual(2, goblin.defense)

        goblin3 = GoblinKing(game)
        game.creatures.append(goblin3)

        self.assertEqual(2, goblin.attack)
        self.assertEqual(3, goblin.defense)

Summary

The Chain of Responsibility pattern enables a sequence of handlers to process a request. Each handler in the chain can choose to act on the request, pass it along, or halt further processing entirely.

There are two common implementations:

  • A linked chain of handlers, where each object holds a reference to the next
  • A centralized dispatcher (e.g., event broker) that maintains a list of handlers and invokes them in order

Key characteristics:

  • Handlers are organized into a chain, and the request flows through them sequentially
  • Each handler can modify, act on, or terminate the flow
  • Handler order can be managed explicitly to establish priority
  • Handlers can be dynamically added, removed, or self-unregistered

This pattern promotes flexibility and decoupling by allowing multiple objects the opportunity to handle a request without tightly coupling the sender to any specific receiver.

← All notes