Decorator (Wrapper)
- Also named Wrapper
- Is a structural pattern
- Add behavior without affect others
- Single Responsibility Principle
- Compose behavior dynamically
- Ex. OutputStream
- Inheritance based
Ex. Create a Sandwich class that will be wrapped by a Decorator to add flavors
- Create the interface for the Component
public interface Sandwich {
public String make();
}
- Create an implementation for the ConcreteComponent that will be decorated
public class SimpleSandwich implements Sandwich{
@Override
public String make() {
return "bread";
}
}
- Create an abstract class for the decorator
public abstract class Decorator implements Sandwich{
protected Sandwich sw;
public Decorator(Sandwich sw){
this.sw = sw;
}
@Override
public String make(){
return sw.make();
}
}
- Create a specific decorator
public class CheeseDecorator extends Decorator{
public CheeseDecorator(Sandwich sw) {
super(sw);
}
public String addIngridient(){
return "cheese";
}
@Override
public String make(){
return sw.make() + addIngridient();
}
}
- Create the main method
- We create a SimpleSandwich and took it to decorated with CheeseDecorator
public class Main {
public static void main (String args[]){
Sandwich sw = new CheeseDecorator(new SimpleSandwich());
System.out.println(sw.make());
}
}
Comentarios
Publicar un comentario