装饰器模式

装饰器模式

这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。


1、创建一个抽象类

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

2、编写抽象类的实现类

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

3、创建实现了 Shape 接口的抽象装饰类

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

4、实现抽象装饰类

 1 public class ReadShapeDecorator extends  ShapeDecorator {
 2     public ReadShapeDecorator(Shape decoratedShape) {
 3         super(decoratedShape);
 4     }
 5     public  void draw(){
 6         decoratedShape.draw();
 7         setRedBorder(decoratedShape);
 8     }
 9 
10     private void setRedBorder(Shape decoratedShape) {
11         System.out.println("Border Color: Red");
12     }
13 
14 }
ReadShapeDecorator

5、测试类

 1 public class DecoratorPatternDemo {
 2     public static void main(String[] args) {
 3         Shape circle = new Circle();
 4         ShapeDecorator readCircle = new ReadShapeDecorator(new Circle());
 5         ShapeDecorator redRectangle = new ReadShapeDecorator(new Rectangle());
 6         circle.draw();
 7         readCircle.draw();
 8         redRectangle.draw();
 9     }
10 }
DecoratorPatternDemo

6、测试结果

1 Circle
2 Circle
3 Border Color: Red
4 Rectangle
5 Border Color: Red
View Code

 转载 :https://www.runoob.com/design-pattern/decorator-pattern.html

原文地址:https://www.cnblogs.com/hoje/p/11933703.html