🎨 Design Patterns

Reusable solutions to common problems

← Back to Architecture

🧩 What is a design pattern?

A design pattern is a tested, reusable solution to a problem programmers face again and again. Instead of reinventing the wheel, you reach for a known recipe — and other developers instantly recognize it.

Patterns aren't code you copy-paste; they're ideas for how to structure your classes. Let's meet three friendly ones.

🏭 Pattern 1: Factory

A factory is a function (or method) whose job is to create objects for you, so the rest of your code doesn't worry about the details.

def make_animal(kind): if kind == "dog": return Dog() if kind == "cat": return Cat() pet = make_animal("dog") # factory decides which class

🎯 Pattern 2: Strategy

The strategy pattern lets you swap behavior by passing in different functions or objects. Same code, different "strategy."

def add(a, b): return a + b def multiply(a, b): return a * b def calculate(a, b, strategy): return strategy(a, b) print(calculate(3, 4, add)) # 7 print(calculate(3, 4, multiply)) # 12

💡 You've used this!

Passing key= to Python's sorted() is the strategy pattern — you give it a strategy for how to compare items.

📣 Pattern 3: Observer

The observer pattern lets many objects "subscribe" to an event. When something happens, everyone gets notified — like followers getting a post update.

class Channel: def __init__(self): self.subscribers = [] def subscribe(self, name): self.subscribers.append(name) def upload(self): return [name + " notified" for name in self.subscribers]

✅ What you learned

  • A pattern is a reusable design idea, not copy-paste code.
  • Factory — a helper that creates objects for you.
  • Strategy — swap behavior by passing in functions/objects.
  • Observer — notify many subscribers when an event happens.