L6·Expert

🏛️Pythonic Design Patterns

Singleton, factory, strategy, observer — the Python way.

patternsSOLIDfactorystrategyobserver

§ 1Functions are objects

Many classic patterns shrink in Python: a Strategy is just a function you pass in; a Factory is a dict mapping names to classes.

§ 2Singleton

A module is already a singleton — import it and share state. Avoid metaclass tricks unless truly needed.

§ 3Observer

Keep a list of callbacks and call them when something changes. Event systems, GUIs and pub/sub all use this.

§ 4SOLID in one line each

Single responsibility · Open for extension · Liskov substitution · Interface segregation · Dependency inversion (pass dependencies in).

Worked example

1# Strategy + Factory + Observer​
2DISCOUNTS = {​
3 "none": lambda p: p,​
4 "festive": lambda p: p * 0.8,​
5 "student": lambda p: p - 50,​
6}​
7​
8class Cart:​
9 def __init__(self):​
10 self.listeners = []​
11 def on_checkout(self, fn):​
12 self.listeners.append(fn)​
13 def checkout(self, price, kind):​
14 total = DISCOUNTS[kind](price)​
15 for fn in self.listeners:​
16 fn(total)​
17 return total​
18​
19cart = Cart()​
20cart.on_checkout(lambda t: print("email receipt:", t))​
21cart.on_checkout(lambda t: print("log sale:", t))​
22cart.checkout(1000, "festive")​

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Simplest Pythonic singleton:

Lesson test

Take an 8-question test on “Pythonic Design Patterns” — concepts, output prediction, bug spotting and interview questions.