Sobes.tech
Junior — Middle

Can you explain the concept and application of the Decorator pattern in object-oriented 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 code. This is especially useful when you need to extend functionality without inheritance.

Example: there is a base interface Beverage with a method cost(). You can create a class Coffee, and then decorators WithMilk, WithSugar, which add to the cost and change behavior.

interface Beverage {
    double cost();
}

class Coffee implements Beverage {
    public double cost() { return 5.0; }
}

class MilkDecorator implements Beverage {
    private Beverage beverage;
    public MilkDecorator(Beverage beverage) { this.beverage = beverage; }
    public double cost() { return beverage.cost() + 1.0; }
}

// Usage
Beverage coffee = new Coffee();
Beverage coffeeWithMilk = new MilkDecorator(coffee);
System.out.println(coffeeWithMilk.cost()); // 6.0

Thus, you can flexibly combine functionality without creating many subclasses.

Can you explain the concept and application of the… - sobes.tech