動態地將責任加諸於物件上,就增加功能來說,裝飾模式比產生子類別更為靈活。
public interface Shape {
public void draw();
}
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("Shape:圓形");
}
}
public class Square implements Shape{
@Override
public void draw() {
System.out.println("Shape:方形");
}
}
public abstract class ShapeDecorator implements Shape{
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;
}
@Override
public void draw() {
decoratedShape.draw();
}
}
public class RedShapeDecorator extends ShapeDecorator{
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape){
System.out.println("Border Color: 紅色");
}
}
public class DecoratorPatternDemo {
public static void main(String[] args) {
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redSquare = new RedShapeDecorator(new Square());
System.out.println("Circle with normal border");
circle.draw();
System.out.println("\nCircle of red border");
redCircle.draw();
System.out.println("\Square of red border");
redSquare.draw();
}
}
Circle with normal border
Shape:圓形
Circle of red border
Shape:圓形
Border Color: 紅色
Square of red border
Shape:方形
Border Color: 紅色