Skip to main content

Decorator Pattern

Learn Decorator Pattern (Structural Patterns, Design Patterns in Java) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.

Decorator Pattern attaches additional responsibilities to an object dynamically , by wrapping it in decorator objects - a flexible alternative to subclassing for extending behavior. Real-Life Example: Coffee shop: base Coffee, then wrap it with Milk, then Sugar, then Whipped Cream - each adds cost/description Java's own BufferedReader(new FileReader(...)) and InputStreamReader chains Why do we need Decorator? To add behavior to individual objects at RUNTIME, without affecting other instances of the same class To avoid an explosion of subclasses for every combination of features (e.g....

More lessons in Structural Patterns