Junior — Middle
Explain the working principle and purpose of the Decorator design pattern.
sobes.tech AI
Answer from AI
The Decorator design pattern allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects. It is an alternative to inheritance for extending functionality.
Working principle:
- There is a base interface or abstract class.
- The original class implements this interface.
- The decorator also implements this interface and contains a reference to an object of the same interface.
- Method calls are delegated to the wrapped object, with the decorator potentially adding additional behavior before or after the call.
Example in Java:
interface Coffee {
String getDescription();
double getCost();
}
class SimpleCoffee implements Coffee {
public String getDescription() { return "Simple coffee"; }
public double getCost() { return 1.0; }
}
class MilkDecorator implements Coffee {
private Coffee coffee;
public MilkDecorator(Coffee coffee) { this.coffee = coffee; }
public String getDescription() { return coffee.getDescription() + ", milk"; }
public double getCost() { return coffee.getCost() + 0.5; }
}
// Usage:
Coffee coffee = new MilkDecorator(new SimpleCoffee());
System.out.println(coffee.getDescription()); // Simple coffee, milk
System.out.println(coffee.getCost()); // 1.5
Thus, the Decorator allows flexible extension of object functionality without modifying their code.