装饰器模式
描述
装饰器模式的作用是在不改变现有对象的结构的情况下,对其添加新的功能。这种模式创建了一个装饰类,该装饰类继承原有的类,并包装原有的类。
描述起来很麻烦,下面举个例子:
假设有个形状接口(shape),下面分别创建长方形类(rectangle)和圆形类(circle)都实现形状接口。下面我要给这两个形状涂上红颜色该怎么办呢?来了啊,装饰器模式就解决了这种状况:创建同样实现了shape接口的抽象装饰类,把shape当成员变量,假设shape有方法a(),呢么装饰类要重写其中的a()方法,并且在重写的方法中默认实现shape.a(),这种操作的目的是为了在继承该抽象类的时候,在不改变shape的结构情况下 ,在a()中添加装饰。
使用场景:当程序员不想增加更多子类的情况下扩展类
实例:
基于上边的例子,我们给出了如下的代码实例:
//形状接口 public interface Shape { void draw(); } //实现形状接口的长方形和圆形类 public class Rectangle implements Shape { @Override public void draw() { System.out.println("Shape: Rectangle"); } } public class Circle implements Shape { @Override public void draw() { System.out.println("Shape: Circle"); } } //实现了shape的抽象装饰器类 public abstract class ShapeDecorator implements Shape { protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape){ this.decoratedShape = decoratedShape; } 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: Red"); } } //演示结果 public class DecoratorPatternDemo { public static void main(String[] args) { Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); System.out.println("Circle with normal border"); circle.draw(); System.out.println("\nCircle of red border"); redCircle.draw(); System.out.println("\nRectangle of red border"); redRectangle.draw(); } }
结果输出:
Circle with normal border Shape: Circle Circle of red border Shape: Circle Border Color: Red Rectangle of red border Shape: Rectangle Border Color: Red
代码来源:特别感谢 菜鸟教程java设计模式之装饰器模式