设计模式(九):装饰模式

113 阅读1分钟

介绍

装饰器模式(Decorator Pattern)属于结构型模式,它允许向一个现有的对象添加新的功能,同时又不改变其结构。

优点

  • 是继承的替代
  • 能够动态扩充对象功能

缺点

  • 多层装饰的话比较复杂

应用

扩展一个类的功能、动态增加功能,动态撤销 Android的Context,ContextWrapper

实现

关键代码

修饰类继承Component抽象类或实现Component接口,具体扩展类重写父类方法

interface Component {
    void draw();
}

class Circle implements Component {
    @Override
    public void draw() {
       System.out.println("Shape: Circle");
    }
}

// RedShapeDecorator并不是Circle子类
class RedShapeDecorator implements Component  {
 
    public RedShapeDecorator(Component decoratedShape) {
       super(decoratedShape);     
    }

    @Override
    public void draw() {
       decoratedShape.draw();         
       setRedBorder(decoratedShape);
    }
  
    private void setRedBorder(Component decoratedShape){
       System.out.println("Border Color: Red");
    }
}

 class DecoratorPatternDemo {
    public static void main(String[] args) {
  
       Component circle = new Circle();
       ShapeDecorator redCircle = new RedShapeDecorator(new Circle());

       System.out.println("Circle with normal border");
       circle.draw();
  
       System.out.println("\nCircle of red border");
       redCircle.draw();
    }
}

运行结果:

Circle with normal border
Shape: Circle

Circle of red border
Shape: Circle
Border Color: Red