Junior — Middle
Kas saaksite selgitada Dekoratsiooni mustri kontseptsiooni ja rakendust objektorienteeritud programmeerimises?
sobes.tech AI
Vastus AI-lt
The Decorator pattern allows for dynamically adding responsibilities to objects by wrapping them in other decorator objects, without changing the source code of the class. This is especially useful when you want to extend functionality without inheritance.
Example: there is a base interface Drink with the method cost(). You can create a class Coffee, and then decorators WithMilk, WithSugar, which add to the cost and change behavior.
interface Drink {
double cost();
}
class Coffee implements Drink {
public double cost() { return 5.0; }
}
class MilkDecorator implements Drink {
private Drink drink;
public MilkDecorator(Drink drink) { this.drink = drink; }
public double cost() { return drink.cost() + 1.0; }
}
// Usage
Drink coffee = new Coffee();
Drink coffeeWithMilk = new MilkDecorator(coffee);
System.out.println(coffeeWithMilk.cost()); // 6.0
This way, you can flexibly combine functionalities without creating many subclasses.