1. Home
  2. Explore
  3. Computer Science
  4. Design Patterns in Python

Study methods

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

Design Patterns in Python

Design Patterns in Python: Concepts and Functional Implementations

The Enduring Relevance of Design Patterns

Design patterns from the Gang of Four (GoF) book are often said to be obsolete, especially in Python where functions can replace many class‑based implementations. However, the lasting value of design patterns lies not in their specific class‑based formulations, but in the problem categories they identify. Whether implemented with classes, functions, or a mix of both, the core goal is decoupling – separating parts of a system so that changes in one area do not ripple through others. Recognizing these problem types (e.g., “I need to swap algorithms at runtime” or “I want to notify multiple components of a change”) is what truly matters for writing flexible, maintainable code.


The Strategy Pattern (Algorithm Exchange)

What It Solves

The strategy pattern allows a system to swap one algorithm for another without the code that uses the algorithm knowing about the change. The consumer simply works with a common interface; the specific algorithm is injected from outside.

Classic Object‑Oriented Implementation

  • An abstract base class (or protocol) defines the strategy interface – e.g., a method sort(data: list[int]) -> list[int].

  • Concrete strategy classes (e.g., BubbleSortStrategy, QuickSortStrategy) implement that interface.

  • A context class holds a reference to a strategy object. It delegates the algorithmic work to whatever strategy is currently attached.

  • The context may perform other operations (e.g., multiplying list elements) and then call the strategy’s method.

Key benefits:

  • The context never knows the concrete strategy – it only depends on the abstract interface.

  • New strategies can be added without modifying the context.

Functional Alternative (Functions as Arguments)

Instead of classes and inheritance, Python allows passing a function as an argument to another function. The “context” becomes a higher‑order function that accepts a callable (the strategy function) as a parameter.

  • Define simple functions: bubble_sort(data: list[int]) -> list[int] and quick_sort(data: ...).

  • The context function takes an extra argument – the sorting function – and applies it.

  • Usage: context(data, bubble_sort) or context(data, quick_sort).

Result: fewer lines of code, still fully decoupled. The core technique is passing a function into another function.

Key Takeaway: The strategy pattern is about recognizing the algorithm‑exchange problem, not about writing abstract classes. Functions achieve the same decoupling with less boilerplate.

Technique Highlight: Higher‑Order Functions

  • A higher‑order function either takes a function as an argument or returns one.

  • This is a foundational idea from functional programming, fully supported in Python.

  • It is not limited to the strategy pattern – it reappears in the observer and template method patterns.


The Observer Pattern (Publish–Subscribe)

What It Solves

The observer pattern addresses the need to notify multiple objects when a change occurs in a subject, without coupling the subject to those objects. Common uses: updating UI after a payment, sending emails/SMS, logging events.

Classic Object‑Oriented Implementation

  • An abstract observer class declares an update(data: str) method.

  • Concrete observers (e.g., LoggingObserver, EmailObserver) implement update.

  • A subject class maintains a list of observer objects. It provides attach(observer), detach(observer), and notify(data) methods.

  • When notify is called, the subject iterates over all attached observers and calls update on each.

Decoupling is achieved because the subject knows only the abstract observer interface – it never depends on concrete observer classes.

Functional Alternative (Functions as Data)

Instead of observer objects, one can use list of callable functions. The subject is replaced by a notify function that accepts a list of update functions and the data to broadcast.

  • Define simple functions: update_observer1(data: str) -> None, update_observer2(data: str) -> None.

  • The notify function takes a list[Callable[[str], None]] and calls each function with the data.

  • Usage: notify([update_observer1, update_observer2], "payment received").

This can be extended with more complex data structures:

  • A dictionary mapping event types to lists of listener functions (e.g., {"payment_success": [send_email, update_ui], "payment_failed": [log_error]}).

The key technique: using a data structure (list, dict) to hold multiple functions and then passing that structure to a higher‑order function.

Key Takeaway: The observer pattern is about the one‑to‑many notification problem. Whether the listeners are objects or functions is implementation detail – the pattern’s value is the decoupled broadcast mechanism.


The Template Method Pattern (Algorithm Skeleton)

What It Solves

The template method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It allows varying parts of an algorithm while keeping the overall structure fixed.

Classic Object‑Oriented Implementation

  • An abstract base class provides:

    • A template method that calls a series of operations in a fixed order.

    • Some base operations with default implementations.

    • Required operations (abstract methods) that subclasses must implement.

    • Hooks – methods with empty or default implementations that subclasses can optionally override.

  • A concrete subclass implements the required operations and optionally overrides hooks.

  • The template method is called on the subclass instance; the fixed skeleton runs but the overridden steps produce different behavior.

Functional Alternative (Functions as Arguments and Return Values)

The same effect can be achieved with pure functions:

  • Define a template function that takes:

    • Required operations as function arguments.

    • Hooks as optional function arguments (with default implementations).

  • The template function calls the operations in order, using the supplied functions.

  • To override a hook, pass a different function; otherwise the default is used.

This yields fewer lines of code and avoids inheritance.

Advanced Techniques: Returning Functions and Partial Application

Returning a function (closure)

  • Instead of passing required operations every time, create a factory function that accepts the required operations once and returns a new function (the configured template) that only needs hooks.

  • Example: def make_template(op1, op2) -> Callable[..., None] returns a template_method function that remembers op1 and op2 via closure.

Partial function application

  • Python’s functools.partial can pre‑apply some arguments to a function, returning a new callable.

  • Example: applied_template = partial(template_method, req_op1, req_op2) creates a function that already has the required operations bound; only hooks need to be supplied when calling.

Key Takeaway: The template method pattern is about keeping a fixed algorithm structure while permitting variations in specific steps. Functions (closures, partial application) achieve this with less code and greater flexibility.

Approach

Lines of Code

Readability

Flexibility

Object‑oriented (classes, inheritance)

~70+

Familiar to OO developers

Rigid (must subclass)

Functions (arguments)

~53

Simple but repetitive if same ops used often

Moderate (need to pass ops each call)

Functions + closure

~60

Harder to read due to nested function

High (ops configured once, reuse)

Functions + partial

~55

Clean, idiomatic

High (ops pre‑applied)


Core Functional Techniques Illustrated

  1. Passing a function as an argument – the backbone of the functional strategy, observer, and template method alternatives.

  2. Returning a function as a result (closure) – allows pre‑configuring a function with some arguments, then calling it later with the remaining arguments.

  3. Using data structures to hold multiple functions – lists, dictionaries, or sets of callables enable sophisticated event‑driven architectures.

  4. Partial function application (functools.partial) – a built‑in that simplifies pre‑setting arguments, especially useful for the template method.


Why Design Patterns Are Not Obsolete

  • The core value of design patterns is identifying a class of recurring problems (algorithm exchange, notification, algorithm skeleton, etc.).

  • The implementation technology (classes, functions, mixins, etc.) is a secondary choice.

  • Knowing these problem categories enables developers to select the right decoupling strategy for the situation – regardless of whether they use inheritance, composition, or higher‑order functions.

  • Even in Python, where functions are first‑class citizens, the problem categories remain relevant. The GoF catalog is still a valuable reference, not for its code examples, but for the abstract solutions it documents.

Final Thought: Design patterns are not relics of the past; they are timeless problem‑solving templates. Master the problem categories, and you can implement them with whatever tools your language provides – classes, functions, or a blend of both.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent