Junior — Middle
Can you explain the mechanism of the Decorator pattern and how it is used in programming?
sobes.tech AI
Answer from AI
The Decorator pattern allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects without changing the original class.
In Java, this is implemented through an interface or an abstract class that is implemented by both the original object and the decorators. The decorator contains a reference to an object of the same type and overrides methods to add additional behavior.
Example:
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
This way, you can flexibly extend the functionality of objects without modifying their code.