🧩 OOP Concepts Intermediate

What is the Decorator pattern?

Why Interviewers Ask This

Mid-level OOP Concepts roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

The Decorator pattern attaches additional responsibilities to an object dynamically. It provides a flexible alternative to subclassing for extending functionality. Key insight: instead of creating a class hierarchy for every combination of features, wrap objects with decorator classes: interface Coffee { double getCost(); String getDescription(); } class SimpleCoffee implements Coffee { public double getCost() { return 1.0; } public String getDescription() { return "Coffee"; } } // Abstract decorator: abstract class CoffeeDecorator implements Coffee { protected Coffee decoratedCoffee; public CoffeeDecorator(Coffee coffee) { this.decoratedCoffee = coffee; } public double getCost() { return decoratedCoffee.getCost(); } public String getDescription() { return decoratedCoffee.getDescription(); } } class MilkDecorator extends CoffeeDecorator { public MilkDecorator(Coffee coffee) { super(coffee); } @Override public double getCost() { return super.getCost() + 0.5; } @Override public String getDescription() { return super.getDescription() + ", Milk"; } } class SugarDecorator extends CoffeeDecorator { @Override public double getCost() { return super.getCost() + 0.25; } @Override public String getDescription() { return super.getDescription() + ", Sugar"; } } // Usage: Coffee myCoffee = new SimpleCoffee(); myCoffee = new MilkDecorator(myCoffee); myCoffee = new SugarDecorator(myCoffee); myCoffee = new MilkDecorator(myCoffee); // Double milk! System.out.println(myCoffee.getDescription()); // Coffee, Milk, Sugar, Milk System.out.println(myCoffee.getCost()); // 2.25. Real uses: Java I/O streams (BufferedInputStream wraps FileInputStream), Spring Security filters, middleware chains, UI component decoration. Benefits: flexible composition of behaviors, avoids subclass explosion, Open/Closed Principle.

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real OOP Concepts project.