Mastering Design Patterns with Examples — Decorator Pattern

Extension at runtime, rather than at compile time

Larry | Peng Yang
Computer Science Fundamentals

--

Photo by Nathan Dumlao on Unsplash

Overview

Let’s review the four OO design principles in the introduction and observer pattern chapters as they are the building blocks to support our design patterns.

  1. Encapsulate what changes
  2. Program to interface, not implementation
  3. Favor composition over inheritance
  4. Loosely coupled designs between objects that interact

In this post, we will be learning another design principle (Open/Closed principle) and a Structural Design Pattern — Decorator Pattern, which is a pattern to decorate objects at runtime.

  • Giving objects new responsibilities at runtime without changing the underlying classes
  • Using composition to avoid class hierarchy explosion due to overuse of inheritance

We will learn it by first looking at how to solve the problem and deepening our understanding with another example using the decorator pattern.

Use decorator pattern in Starbuzz Coffee problem

Let’s take a look at the Starbuzz Coffee problem in the Head First Design Pattern book.

--

--