Sobes.tech
Middle+

Explain the Decorator pattern — how does it work?

sobes.tech AI

Answer from AI

The Decorator pattern allows dynamically adding new responsibilities to objects by wrapping them in "wrappers" — decorators that implement the same interface as the original object.

How it works:

  • There is a basic interface or abstract class.
  • A concrete object implements this interface.
  • The decorator contains a reference to an object of the same interface and implements additional functions by calling methods of the wrapped object and augmenting them.

This allows flexible extension of object behavior without changing their code and without creating a large number of subclasses.

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() + ", with milk";
    }
    public double getCost() {
        return coffee.getCost() + 0.5;
    }
}

// Usage:
Coffee coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee);
System.out.println(coffee.getDescription()); // Simple coffee, with milk
System.out.println(coffee.getCost()); // 1.5

Thus, decorators allow adding functionality to objects on the fly without changing their original code.