The Decorator Pattern attaches additional responsibilities to an object dynamically at runtime. Instead of using inheritance to add features from the top down, you wrap the original object inside a "decorator" object that adds the new behavior, like Russian nesting dolls.

image.png

The Problems It Solves

When to Use It

image.png

Step-by-Step Implementation

1. The Base Component (The Core Interface)

Everything must implement this so the wrappers and the base objects share the exact same type.

public abstract class Beverage{
    public abstract String getDescription();
    public abstract double cost();
}

2. The Concrete Component (The Inner Doll)

This is the base object that will eventually get wrapped. It hardcodes its own baseline identity and price.

public class Espresso extends Beverage{
    @Override
    public String getDescription(){
        return "Espresso";
    }

    @Override
    public double cost(){
        return 1.99;
    }
}

3. The Base Decorator (The Wrapper)

This intermediate class forces all condiments to be interchangeable with Beverages, while mandating they hold a reference to the thing they are wrapping.