参考来源:http://www.runoob.com/design-pattern/decorator-pattern.html
-
介绍
装饰器模式允许向一个添加新的功能,但是有不改变其结构。这种模式创建一个用于包装原始类的装饰类,在保证原始类方法签名不变的情况下提供新的功能。
-
作用
- 在不想增加很多子类的情况下扩展类;
- 作为继承的替代方式,而且类之间不会相互耦合;
-
实现
在本例中,我们将创建一个Shape接口和实现Shape接口的实体类。然后我们定义抽象装饰类ShapeDecorator,用于所有实现Shape接口的实体类的装饰。
- 创建Shape接口
public interface Shape { void draw(); }
- 创建实现Shape接口的实体类
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(); } }
- 创建扩展ShapeDecorator类的实体装饰类
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"); } }
- 使用RedShapeDecorator装饰Shape对象
public class DecoratorPatternDemo { public static void main(String[] args) { Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle());//装饰Shape对象 Shape redRectangle = new RedShapeDecorator(new Rectangle());//装饰Shape对象 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(); } }