Skip to main content

Structural - Decorator

In object-oriented programming, thedecorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.The decorator pattern is structurally nearly identical to the chain of responsibility pattern, the difference being that in a chain of responsibility, exactly one of the classes handles the request, while for the decorator, all classes handle the request.

Starbuzz Coffee

image

Adding Ingredients: First Try

image- But what if we want more ingredients? Open-closed principle?

Adding Ingredients: Second Try

image

What we want:

  • Adding a new ingredient like soy milk should not modify the original beverage classes
  • Adding new ingredients should be simple and work automatically across all beverages

Solution: Decorator Pattern

image

  • Composition solves the problem
  • Note: Do not confuse this with Python function decorators