Decorator Pattern
Some objects need extras that can be combined freely. A pizza can have cheese, then mushrooms, then extra cheese again. A coffee can have milk, a syrup and whipped cream. A data source can be compressed, encrypted, cached, or all three. Each extra adds a little behavior on top of what was already there, and customers pick any mix.
The Decorator pattern makes each extra a small wrapper object. A wrapper looks exactly like the thing it wraps, so you can wrap a wrapper, and stack as many as you need at runtime.
🧩 In one sentence: wrap an object in another object with the same interface that adds one piece of behavior and forwards everything else, so extras can be stacked in any order and any number.
The Problem It Solves
Here is a pizza price calculator, written the way it often starts: one class with a flag per topping.
class Pizza:
def __init__(self, size: str, cheese: bool = False, mushrooms: bool = False,
pepperoni: bool = False, extra_cheese: bool = False) -> None:
self.size = size
self.cheese = cheese
self.mushrooms = mushrooms
self.pepperoni = pepperoni
self.extra_cheese = extra_cheese
def price(self) -> int:
cents = {"small": 800, "medium": 1_000, "large": 1_200}[self.size]
if self.cheese:
cents += 150
if self.mushrooms:
cents += 100
if self.pepperoni:
cents += 200
if self.extra_cheese:
cents += 150
return cents
def description(self) -> str:
parts = [f"{self.size} pizza"]
if self.cheese:
parts.append("cheese")
# ...one line per topping, again
return ", ".join(parts)
It works for four toppings. Then the menu grows.
Every new topping edits the class. Adding olives means a new constructor argument, a new branch in price
and another in description. Working code is reopened for every menu change, which breaks the open/closed
principle.
Quantities don't fit. A customer wants triple pepperoni. A boolean can't say that, so extra_cheese already
exists as a hack, and soon you have extra_pepperoni, double_extra_cheese...
Order is lost. Some rules depend on order: "a half-price promo applies to everything added so far" or "the receipt lists toppings in the order the customer chose them". A set of flags has no order.
The other obvious fix is inheritance: CheesePizza, CheeseMushroomPizza, CheeseMushroomPepperoniPizza. With
five toppings that is up to 32 classes, and with repeats it never ends. This is called a class explosion:
subclasses multiply because every combination needs its own class.
⚠️ The smell to look for: a growing set of boolean flags or optional extras that each add a bit to the same methods, or subclasses named after combinations (
LoggingCachingClient). That is the cue for Decorator.