Explain the Decorator pattern.

Topic: design-patterns, Structural Patterns. Level: Intermediate.

Answer

Decorator dynamically **adds responsibilities** to an object by wrapping it in a decorator that implements the same interface and delegates to the wrapped object, adding behavior before/after. It's a flexible alternative to subclassing for extending behavior — you can stack decorators in any combination at runtime (Open/Closed). Java I/O (`BufferedInputStream` wrapping `FileInputStream`) is the classic example. ```java interface Coffee { double cost(); String desc(); } class Espresso implements Coffee { public double cost(){ return 2.0; } public String desc(){ return "espresso"; } } abstract class CoffeeDecorator implements Coffee { protected final Coffee inner; // same interface, wraps one CoffeeDecorator(Coffee c){ inner = c; } } class Milk extends CoffeeDecorator { Milk(Coffee c){ super(c); } public double cost(){ return inner.cost() + 0.5; } // add behavior public String desc(){ return inner.desc() + "+milk"; } } class Sugar extends CoffeeDecorator { Sugar(Coffee c){ super(c); } public double cost(){ return inner.cost() + 0.2; } public String desc(){ return inner.desc() + "+sugar"; } } // Stack decorators at runtime: Coffee c = new Sugar(new Milk(new Espresso())); // cost 2.7, "espresso+milk+sugar" ```