Junior
What is the purpose of a decorator in programming?
sobes.tech AI
Answer from AI
Decorator is used for dynamically adding responsibilities to an object. It wraps the original object and delegates method calls, while adding or modifying behavior before or after the main method call. This allows extending functionality without changing the original class. The main advantage is flexible combination of different decorators.
// Interface defining the basic functionality
interface Component {
String operation();
}
// Concrete class implementing the interface
class ConcreteComponent implements Component {
@Override
public String operation() {
return "Basic function";
}
}
// Abstract decorator class
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public String operation() {
return component.operation();
}
}
// Concrete decorator adding new behavior
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public String operation() {
return "Decorator A(" + super.operation() + ")";
}
}
// Another concrete decorator
class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public String operation() {
return "Decorator B(" + super.operation() + ")";
}
}
/*
// Usage example:
public class Main {
public static void main(String[] args) {
Component simple = new ConcreteComponent();
System.out.println("Simple object: " + simple.operation());
Component decoratorA = new ConcreteDecoratorA(simple);
System.out.println("Object with decorator A: " + decoratorA.operation());
Component decoratorB = new ConcreteDecoratorB(decoratorA);
System.out.println("Object with decorators A and B: " + decoratorB.operation());
}
}
*/
Comparison with inheritance:
| Aspect | Decorator | Inheritance |
|---|---|---|
| Extension | Dynamic addition of behavior at runtime | Static extension at compile time |
| Flexibility | Easily combine multiple decorators | Creates rigid class hierarchy |
| Multiple functions | Each decorator adds one function | Multiple class increases when adding functions |
| Behavior change | Wraps the object without changing its class | Requires modification of base or derived class |