๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Creational and Behavioral Design Patterns in Python

Python InterviewSoftware Architectureโญ Premium
Python Interview ยท Difficulty: Medium-Hard

Patterns are named solutions to recurring pressure

Design patterns earn their keep when they answer a pressure you actually feel: objects that must be created without coupling the caller to concrete classes, algorithms that must be swapped at runtime, actions that must be undone, events that must fan out without the source knowing the listeners. In a Python interview, the trap is reciting a Java-flavoured catalog. The winning approach names the pressure first, picks the smallest pattern that relieves it, and then shows the Pythonic implementation โ€” often a function, a dict dispatch, or a module-level object where a Java interview would need an interface and a factory class. Below are the patterns interviewers still ask for, each with its Python-native form and the moment you should choose it.

Prerequisites

  • !Classes, ABCs, and decorators
  • !Modules and imports as a namespace mechanism

What You'll Learn

  • 1Implement thread-safe singleton and explain why a module is usually better
  • 2Build factory-registry systems that plugins can extend without core edits
  • 3Apply strategy and adapter to swap algorithms and reconcile foreign interfaces
  • 4Design command histories and observer emitters that handle unsubscription cleanly

Creational: singleton, factory, and builder

The singleton pattern guarantees one instance of a class per process. The metaclass version intercepts instantiation through __call__ and caches the result; the decorator version wraps the class in a function that memoizes instances. Both make tests harder and hidden state likelier, so the mature interview answer leads with the alternative: a module-level instance is Python's native singleton โ€” import it everywhere, get one object, and let the import system handle locking and caching. Use an explicit singleton class only when you need lazy initialization, per-subclass singletons, or reset support for tests.

Factory work in Python usually collapses into a registry dict. A base class documents the interface, concrete classes implement it, and a factory maps string keys to classes. The elegance is in extensibility: third-party plugins call register("webp", WebpEncoder) at import time, and the factory never imports the plugin. A factory method on the base class (Notification.create(kind, **config)) is the lighter variant when the set of products is closed and known.

The builder pattern solves constructors with many optional parameters. A fluent builder whose methods return self makes call sites readable, and build() centralizes required-field validation. Before reaching for a builder in real code, check whether keyword-only arguments or a frozen dataclass with __post_init__ validation solve the same problem with less machinery โ€” saying that out loud demonstrates taste.

python
from abc import ABC, abstractmethod


class Notification(ABC):
    @abstractmethod
    def send(self, message: str) -> bool:
        ...


class EmailNotification(Notification):
    def __init__(self, smtp_server: str):
        self.smtp_server = smtp_server

    def send(self, message: str) -> bool:
        print(f"email via {self.smtp_server}: {message}")
        return True


class SmsNotification(Notification):
    def __init__(self, api_key: str):
        self.api_key = api_key

    def send(self, message: str) -> bool:
        print(f"sms via api: {message}")
        return True


class NotificationFactory:
    _registry = {}

    @classmethod
    def register(cls, kind, product):
        cls._registry[kind] = product

    @classmethod
    def create(cls, kind, **kwargs):
        if kind not in cls._registry:
            raise ValueError(f"unknown kind: {kind}")
        return cls._registry[kind](**kwargs)


NotificationFactory.register("email", EmailNotification)
NotificationFactory.register("sms", SmsNotification)

notifier = NotificationFactory.create("email", smtp_server="smtp.example.com")
notifier.send("deploy finished")

Structural: adapter for foreign interfaces

The adapter pattern wraps an object with an incompatible interface and translates calls to the shape your code expects. In Python the pressure appears when integrating third-party SDKs, legacy internal libraries, or data sources that return XML while the rest of the system speaks JSON. A thin adapter class with explicit methods documents the translation; a duck-typed wrapper that simply renames methods can be even thinner. The interview-worthy insight is that adapters localize the ugliness: when the vendor changes their SDK, only the adapter changes.

Python offers a lighter alternative worth naming โ€” monkeypatching or a small wrapper function โ€” but adapters win when the translation has state, validation, or multiple methods. Show one adapter for a payment gateway and mention that you would write one per vendor behind a common interface so the checkout flow never learns vendor names.

Behavioral: strategy, command, observer

Strategy extracts interchangeable algorithms behind a common interface. In Python the "interface" can be a plain callable: a sort function that accepts key=, a pricing module that dispatches through a dict of strategies, or an ABC when you want explicit contracts and type checking. The conversation to have with the interviewer: strategy versus inheritance. Inheritance couples the class hierarchy to the algorithm family; strategy composes, so algorithms can be selected at runtime, tested in isolation, and extended without subclass explosion.

Command wraps an action as an object with execute and undo, enabling undo stacks, redo, queued execution, and audit logs. The text editor demo is standard; a shopping cart or an infrastructure provisioning tool shows the same shape at larger scale. The design detail interviewers look for: execute records whatever undo needs โ€” deleted text, previous values โ€” at execution time, not at construction time, because the world may change between the two.

Observer fans events out to subscribers who register interest. An EventEmitter with on, once, and emit is fifteen lines; production versions add weak references, thread safety, and unsubscribe handles. The Pythonic twist is that listeners can be plain functions or bound methods โ€” and bound methods must be stored weakly or the emitter keeps every subscriber alive forever. Returning an unsubscribe function from on is the ergonomic API that modern event libraries converged on.

python
class TextDoc:
    def __init__(self):
        self.content = ""

    def insert(self, text, position):
        self.content = self.content[:position] + text + self.content[position:]

    def delete(self, position, length):
        removed = self.content[position:position + length]
        self.content = self.content[:position] + self.content[position + length:]
        return removed


class InsertCommand:
    def __init__(self, doc, text, position):
        self.doc, self.text, self.position = doc, text, position

    def execute(self):
        self.doc.insert(self.text, self.position)

    def undo(self):
        self.doc.delete(self.position, len(self.text))


class History:
    def __init__(self):
        self._undo, self._redo = [], []

    def run(self, command):
        command.execute()
        self._undo.append(command)
        self._redo.clear()

    def undo(self):
        if not self._undo:
            return False
        cmd = self._undo.pop()
        cmd.undo()
        self._redo.append(cmd)
        return True

    def redo(self):
        if not self._redo:
            return False
        cmd = self._redo.pop()
        cmd.execute()
        self._undo.append(cmd)
        return True


doc, history = TextDoc(), History()
history.run(InsertCommand(doc, "Hello", 0))
history.run(InsertCommand(doc, " World", 5))
history.undo()
print(doc.content)  # Hello

Choosing the pattern: a decision table

Interviewers sometimes flip the direction โ€” giving a scenario and asking which pattern fits. The table below compresses that mapping, and having it memorized lets you answer in one sentence and move to the implementation they really wanted to see. If two patterns seem to fit, name both, pick the smaller one, and explain the pressure that forced the choice; that reasoning is what earns the point.

Scenario pressurePatternPythonic form
One shared instance, lazy initSingletonModule-level object first; metaclass if needed
Create objects without naming classesFactory + registryDict of key to class; plugins self-register
Constructor with many optional knobsBuilder or keyword-only argsFluent builder returning self
Swap algorithms at runtimeStrategyCallables or ABC; dict dispatch
Undo, audit, queued actionsCommandObjects with execute/undo; history stacks
Fan out events to subscribersObserverEventEmitter with weakref listeners
Reconcile a foreign interfaceAdapterThin wrapper with explicit methods

Pattern combinations appear in real systems

Production designs rarely use one pattern in isolation. A plugin system combines factory registration with observer events when plugins announce their readiness. An editor combines command history with observer notifications so the UI re-renders after undo. A payment flow combines strategy (which processor) with adapter (vendor SDK) and decorator-style retry around the call. When an interviewer describes a system and asks you to decompose it, naming two or three interacting patterns and sketching their seams is more convincing than a single perfect pattern in isolation. Close by noting the Python-specific shortcuts โ€” module singletons, dict dispatch, callable strategies, __init_subclass__ registration โ€” because those show you write Python for production, not translated Java.

Common Mistakes

Implementing a thread-unsafe singleton by checking an instance dict without a lock

Fix: Guard with a lock or, better, use a module-level instance created at import

Building a class hierarchy for strategies that are just functions

Fix: Accept callables; add an ABC only when you need enforced methods or typing

Storing strong references to subscriber bound methods

Fix: Use weakref.WeakMethod and prune dead references during emit

Computing undo state lazily at undo time

Fix: Snapshot the affected data at execute time, when it is still known

Best Practices

  • Name the pressure the pattern relieves before naming the pattern
  • Prefer the smallest mechanism: module, dict, callable โ€” escalate to classes only when needed
  • Make plugin registration side-effect-free and documented; hidden import-order magic breaks deployments
  • Document undo and failure semantics for command systems; they are where bugs hide

Interview Questions

Q1: When would you use a factory over direct instantiation?

When the concrete class is chosen from configuration, plugins, or runtime state; when you want to centralize validation or caching of products; or when the caller should not depend on the concrete class at all.

Q2: How do you implement a thread-safe singleton in Python?

A metaclass or decorator with double-checked locking around instance creation โ€” or simply a module-level instance, which the import system already initializes exactly once.

Q3: Observer versus publish-subscribe?

Observer keeps a direct link between subject and subscribers, usually synchronous. Pub-sub inserts a broker, decoupling producers from consumers entirely and enabling cross-service messaging.

Q4: When is strategy better than inheritance?

When algorithms vary independently of the data type, when you need runtime selection, or when you want to test algorithms in isolation. Inheritance is fine for fixed is-a relationships with stable behavior.

Q5: How do you handle command serialization?

Store the command type plus its arguments as data (JSON or similar), reconstruct commands on replay, and ensure undo state is either re-derivable or persisted with the command.

Key Takeaways

  • Pick patterns by pressure, not by catalog familiarity
  • Module singletons, dict factories, and callable strategies are the Python-native forms
  • Adapters localize third-party mess; strategy swaps behavior without subclass explosion
  • Command systems must snapshot undo state at execute time
  • Observer implementations need weak references and unsubscribe handles to survive production
  • Real designs combine patterns โ€” name the seams when decomposing a system
๐Ÿ”’

Premium Content

Creational and Behavioral Design Patterns in Python

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement