Decorator Design Pattern
package com.javaletters.sample.designpattern;
public interface room{
public String showRoom();
}
The above is an interface depicting an room. I have kept things as simple as possible so that the focus will be on understanding the design pattern. Following class is a concrete implementation of this interface. This is the base class on which the decorators will be added.
package com.javaletters.sample.designpattern;
public class SimpleRoom implements Icecream {
@Override
public String showRoom() {
return "Normal Room";
}
}
Following class is the decorator class. It is the core of the decorator design pattern. It contains an attribute for the type of interface. Instance is assigned dynamically at the creation of decorator using its constructor. Once assigned that instance method will be invoked.
package com.javaletters.sample.designpattern;
abstract class RoomDecorator implements Room{
protected Room specialRoom;
public RoomDecorator (Room specialRoom) {
this.specialRoom= specialRoom;
}
public String showRoom() {
return specialRoom.showRoom();
}
}
Following two classes are similar. These are two decorators, concrete class implementing the abstract decorator. When the decorator is created the base instance is passed using the constructor and is assigned to the super class. In the showRoom method we call the base method followed by its own method addColors(). This addColors() extends the behavior by adding its own steps.
package com.javaletters.sample.designpattern;
public class ColorDecorator extends RoomDecorator {
public ColorDecorator (Room specialRoom) {
super(specialRoom);
}
public String showRoom() {
return specialRoom.showRoom() + addColors();
}
private String addNuts() {
return " + Blue Color";
}
}
package com.javaletters.sample.designpattern;
public class CurtainDecorator extends RoomDecorator {
public CurtainDecorator (Room specialRoom) {
super(specialRoom);
}
public String showRoom() {
return specialRoom.showRoom() + addCurtains();
}
private String addCurtain() {
return " + Red Curatains";
}
}
Execution of the decorator pattern
I have created a simple Room and decorated that with color and curatains. We can use as many decorators in any order we want. This excellent flexibility and changing the behaviour of an instance of our choice at runtime is the main advantage of the decorator design pattern.
package com.javaletters.sample.designpattern;
public class TestDecorator {
public static void main(String args[]) {
Room room = new CurtainDecorator(new ColorDecorator(new SimpleRoom()));
System.out.println(room.showRoom());
}
}
Output
Normal room + Blue Color + Red Curtains
Decorator Design Pattern in java API
java.io.BufferedReader; java.io.FileReader; java.io.Reader; The above readers of java API are designed using decorator design pattern.