Learnings

Python design, part 2 of 2

Python Design Patterns

A design pattern is a named solution to a problem that keeps coming back. All 23 classic patterns, grouped into their three families: creational, structural and behavioural. Each one is shown in a few lines on the same small bank, with the problem it solves and the shortcut Python gives you. Examples run on Python 3.9 or newer with only the standard library.

The bank we will use

The same two classes as in Design Principles. Save this as bank.py. Every pattern imports from it.

What the three families mean

The classic catalogue has 23 patterns. It comes from the 1994 book Design Patterns, whose four authors are known as the Gang of Four. They sorted the patterns by the kind of problem each one solves, which gives three families.

FamilyThe word meansQuestion it answersIn our bank
CreationalAbout creating objectsWho decides which object gets made, and how?Opening the right kind of account, putting a loan together
StructuralAbout structure: how objects are joined into larger piecesHow do separate pieces fit together?A card in front of an account, a family portfolio of accounts
BehaviouralAbout behaviour: how objects talk and share work while the program runsWho does what, and how do they tell each other?Approvals, alerts, undo, interest rules

Picture a house: creational is how the bricks and rooms get made. Structural is how the rooms are joined into a house. Behavioural is how the people living in it talk to each other and share the chores.

The rest of this page follows that order. Every pattern chapter is labelled with its family.

Creational patterns

Family 1 of 3 · how objects are made

Writing Account(owner) is the simplest way to create an object, and usually the right one. It stops being enough when the code that needs the object should not know its exact class, when the object takes several steps to put together, or when only one copy is allowed to exist.

Creational patterns move the decision about what gets made and how into one place, so the rest of the program just asks for an object and uses it.

Factory method

Creational pattern

Problem: the caller knows the kind of account as a string, from a form or an API, and should not need to know which class that means.

A factory is one function that picks the class and returns the object.

The classic form: a subclass decides

In the textbook version the parent class runs the steps and calls a method, the factory method, that each subclass overrides to say which class to create.

Python shortcut: classes are objects, so a dictionary from name to class replaces the class hierarchy of factories that other languages need.

Abstract factory

Creational pattern

Problem: some objects only make sense together. A premium customer gets a premium account and a platinum card. Mixing a premium account with a classic card would be a bug.

An abstract factory is an object that makes a whole matching set. Choose the factory once and everything it produces belongs together.

Factory method or abstract factory? A factory method makes one object. An abstract factory makes a family of related objects and guarantees they match.

Builder

Creational pattern

Problem: an object has many optional parts and must be valid before anyone uses it. A loan needs an amount and a term, and may have guarantors and insurance.

A builder collects the parts step by step and checks them once in build().

Python shortcut: for most objects, keyword arguments with defaults are enough. Use a builder when construction has steps or validation across several fields.

Prototype

Creational pattern

Problem: new objects should start as a copy of a prepared one. Every student account opens with the same balance and perks.

Watch out: copy.copy() is shallow, so both accounts would share one perks list and the travel card would appear on both.

Singleton

Creational pattern

Problem: the whole program must share one object, such as the bank's settings.

Python shortcut: a module is already a singleton. Put daily_limit = 50000 in settings.py and import settings everywhere. Use this pattern sparingly: shared global state makes tests depend on each other.

Structural patterns

Family 2 of 3 · how objects fit together

Once objects exist, they have to be connected. Structural patterns describe ways to wrap, combine or stand in front of objects so that pieces written separately can work together.

The common idea is that you change how things are joined, not the classes themselves. An account stays an account. What changes is what you put around it or next to it.

  • Adapter: make an object with the wrong interface usable
  • Bridge: let two things vary without multiplying classes
  • Composite: treat one item and a group of items alike
  • Decorator: wrap an object to add behaviour
  • Facade: put one simple door in front of many parts
  • Flyweight: share one object instead of making many copies
  • Proxy: stand in front of an object and control access to it

Adapter

Structural pattern

Problem: code you cannot change has the wrong interface. The old UPI library wants an ID and paise, while the bank works with people and rupees.

An adapter wraps the old object and translates the call.

Bridge

Structural pattern

Problem: two things vary independently. The bank has kinds of alert (deposit, low balance) and ways to send them (SMS, email). One subclass per combination means 2 × 2 classes today and 3 × 3 tomorrow.

A bridge keeps the two sides as separate small hierarchies and connects them with a reference. Each side grows without touching the other.

Count the classes: four combinations from four small classes. Adding WhatsApp is one more class, and every alert can use it immediately.

Composite

Structural pattern

Problem: treat one item and a group of items the same way. A family's money is a tree: the family holds groups, and groups hold accounts.

Give the group the same balance attribute as a single account, and let it add up its children.

Decorator

Structural pattern

Problem: add behaviour to an object without changing its class, and allow several additions to be stacked.

A decorator wraps an object, has the same methods, and does something extra before or after passing the call on.

Function decorators

Python has the same idea built into the language for functions, written with @.

Facade

Structural pattern

Problem: one task needs several subsystems in the right order. A transfer must pass KYC and fraud checks, move the money and write the ledger.

A facade gives callers one simple method and hides the steps behind it.

Flyweight

Structural pattern

Problem: a huge number of objects repeat the same data. A million accounts belong to a few hundred branches, and each one does not need its own copy of the branch details.

A flyweight is one shared object that many others point to. A small function hands out the existing one and only creates it the first time.

Python shortcut: put @functools.lru_cache on a function that builds the object and you get the same sharing without writing the dictionary. Shared objects must not be modified, because every holder would see the change.

Proxy

Structural pattern

Problem: control access to an object. A debit card stands in front of the account and lets a withdrawal through only with the right PIN.

Proxy or decorator? Both wrap an object. A decorator adds behaviour. A proxy decides whether, when or how the real object is reached: permissions, caching, lazy loading.

Behavioural patterns

Family 3 of 3 · how objects talk and share work

Behavioural patterns are about what happens while the program runs: which object is responsible for a piece of work, how objects tell each other that something happened, and how a step can be swapped without rewriting the code that calls it.

This is the largest family, because most of what a program does is objects passing work and messages to each other.

  • Chain of responsibility: pass a request along until someone handles it
  • Command: turn an action into an object you can store and undo
  • Interpreter: run instructions written in a tiny language
  • Iterator: loop over a collection without seeing inside it
  • Mediator: let objects talk through one hub, not to each other
  • Memento: save an object's state and restore it later
  • Observer: tell everyone who is interested when something happens
  • State: change behaviour when the object's condition changes
  • Strategy: swap the way a job is done
  • Template method: fix the steps, let subclasses fill some in
  • Visitor: add a new operation without touching the classes

Chain of responsibility

Behavioural pattern

Problem: a request should be handled by the first one able to, and the sender should not need to know who that is. A large withdrawal climbs from teller to manager to director.

Command

Behavioural pattern

Problem: you want to queue, log or undo actions. That is impossible while an action is only a method call that has already happened.

Turn each action into an object that knows how to do itself and how to reverse itself.

Interpreter

Behavioural pattern

Problem: people who do not write Python need to describe what should happen. Standing instructions arrive as plain text, one per line.

An interpreter defines a tiny language and runs it. Here every line is a verb and an amount, and a dictionary maps each verb to the method that carries it out.

Keep it tiny: this pattern suits very small languages such as rules, filters or scripts like this one. For anything bigger, use an existing format (JSON, YAML) or a parsing library.

Iterator

Behavioural pattern

Problem: let callers loop over a collection without knowing how it is stored inside.

Python builds this into the language: define __iter__ and the object works in for loops, sum(), list() and comprehensions.

Mediator

Behavioural pattern

Problem: many objects need to interact, and if each one knows all the others, every new object means editing all of them.

A mediator is a hub in the middle. Each object knows only the hub, and the hub decides who else is involved.

Mediator or facade? A facade is a one-way front door: callers use it, and the parts behind it do not know it exists. A mediator sits between equals that all talk through it.

Memento

Behavioural pattern

Problem: you want to go back to how an object was, without the outside world poking at its internals. Three bills are paid in a batch, and if one fails, none of them should count.

A memento is a snapshot the object makes of itself and can later restore from.

Memento or command? Both give you undo. A command remembers the action and reverses it. A memento remembers the state and puts it back, which is simpler when many things changed at once.

Observer

Behavioural pattern

Problem: when something happens, several other parts need to know, and the source should not have to know who they are. A deposit triggers an SMS and a passbook entry.

Payoff: adding an email alert is one new function and one line to register it. WatchedAccount does not change.

State

Behavioural pattern

Problem: an object behaves differently depending on its condition, and every method is filling up with if self.status == ... checks.

Move the behaviour for each condition into its own class and let the account hold the current one.

State or strategy? The shape is the same. A strategy is chosen by the caller and usually stays. A state changes during the object's life, often by itself.

Strategy

Behavioural pattern

Problem: one job can be done in several ways, and the choice is made at run time. Interest can be simple or compound.

Put each way in its own interchangeable piece and pass in the one you want.

Python shortcut: functions can be passed around like any value, so a strategy is usually a plain function. Use a class when the strategy needs its own settings or several methods.

Template method

Behavioural pattern

Problem: several variants share the same steps in the same order, and differ only in a few of them. Every statement has a header, rows and a footer, whatever the format.

The parent class fixes the order. Subclasses fill in or replace individual steps.

Visitor

Behavioural pattern

Problem: you keep needing new reports over the same set of classes (interest this month, tax next month) and do not want to add a method to every class each time.

Each class gets one accept() method that hands itself to a visitor. Every new report is then a new visitor class, and the account classes never change again.

Python shortcut: functools.singledispatch lets you write one function per class without any accept() methods. Use a visitor when new operations are common and new classes are rare. If it is the other way round, ordinary methods are simpler.

Which pattern to pick

Start from the problem, not from the pattern.

You need toPatternFamily
Create the right class from a name or settingFactory methodCreational
Make a set of objects that must matchAbstract factoryCreational
Assemble an object with many optional partsBuilderCreational
Start new objects as copies of a prepared onePrototypeCreational
Share exactly one object everywhereSingletonCreational
Use code whose interface does not fitAdapterStructural
Combine two things that vary independentlyBridgeStructural
Treat one item and a group alikeCompositeStructural
Add stackable behaviour without subclassingDecoratorStructural
Hide several steps behind one callFacadeStructural
Stop storing the same data thousands of timesFlyweightStructural
Control access to an objectProxyStructural
Pass a request along until someone handles itChain of responsibilityBehavioural
Queue, log or undo actionsCommandBehavioural
Run instructions written as textInterpreterBehavioural
Loop over a collection without exposing itIteratorBehavioural
Stop objects from all knowing each otherMediatorBehavioural
Save state and roll back to itMementoBehavioural
Tell others when something happensObserverBehavioural
Change behaviour as an object's condition changesStateBehavioural
Swap the way a job is doneStrategyBehavioural
Share fixed steps with a few variable onesTemplate methodBehavioural
Add operations without editing the classesVisitorBehavioural

Remember KISS and YAGNI: a pattern is worth its extra classes only when the problem it solves is really there. If a plain function does the job, use the function. See Design Principles.