Mastering Design Patterns with Examples — Decorator Pattern
Extension at runtime, rather than at compile time
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.
- Encapsulate what changes
- Program to interface, not implementation
- Favor composition over inheritance
- 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.