装饰器模式其实就是静态代理模式,与目标对象实现相同的接口然后对其进行一次包装,上代码。

1 代码实现

代码来自菜鸟教程

创建 Shape 接口

1
2
3
public interface Shape {
   void draw();
}

创建一个 Rectangle

1
2
3
4
5
6
7
public class Rectangle implements Shape {
 
   @Override
   public void draw() {
      System.out.println("Shape: Rectangle");
   }
}

封装一个抽象装饰者

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public abstract class ShapeDecorator implements Shape {
   protected Shape decoratedShape;
 
   public ShapeDecorator(Shape decoratedShape){
      this.decoratedShape = decoratedShape;
   }
 
   public void draw(){
      decoratedShape.draw();
   }  
}

实现一个实际的装饰者

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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: Red");
   }
}

测试代码

1
2
3
4
5
6
7
public class DecoratorPatternDemo {
   public static void main(String[] args) {
 
      ShapeDecorator redRectangle = new RedShapeDecorator(new Rectangle());
      redRectangle.draw();
   }
}

其实就是在实际代码运行之前、之后或是抛出异常时添加一些别的代码。

参考资料

  1. 装饰器模式