Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
AKA: Wrapper
Classes should be open for extension, but closed for modification
public interface Duck{
String fly();
}
public class BasicDuck implements Duck{
private final FlyStrategy strategy;
public BasicDuck(final FlyStrategy strategy){
this.strategy = strategy;
}
// ...
}
public class StrongDuck implements Duck{
private final Duck wrapped;
public StrongDuck(final Duck d){
this.wrapped = d;
}
public String fly(){
return wrapped.fly() + wrapped.fly();
}
}
We can think of a decorator as a skin over an object that changes its behavior. […] The strategy pattern is a good example of a pattern changing the guts.