Decorator Design Pattern in Java

Decorator adds new features to an object by wrapping it, without changing its class.

Real life example

Adding milk and sugar to a coffee. Each extra changes the price, but it is still a coffee.

When to use

You want to add features at run time and do not want a subclass for every combination.

Complete Java example

Save this as Main.java, then run javac Main.java and java Main.

public class Main {
    public static void main(String[] args) {
        Coffee c = new Sugar(new Milk(new SimpleCoffee()));
        System.out.println(c.cost());                               // 65.0
    }
}

interface Coffee { double cost(); }

class SimpleCoffee implements Coffee { public double cost() { return 50; } }

class Milk implements Coffee {
    private Coffee coffee;
    Milk(Coffee c) { coffee = c; }
    public double cost() { return coffee.cost() + 10; }     // wrap and add
}
class Sugar implements Coffee {
    private Coffee coffee;
    Sugar(Coffee c) { coffee = c; }
    public double cost() { return coffee.cost() + 5; }
}

Output

65.0