动态或者静态地为一个对象附加一个职责或者功能,称为装饰模式。它是属于结构设计模式之一,比较常用。
使用场合和优势:
- 为子类提供了一个可选项。
- 在不影响其它对象的前提下,给一个对象添加一个新方法。
- 很容易动态地添加和删除某个职责。
- 比静态继承更具有灵活性。
- 对于对象来说是透明的。
下列UML类图展示了装饰模式的经典实现模型。
我们将要定义一个Shape接口和图的实现类。之后,我们创建抽象装饰类ShapeDecorator,它实现了Shape接口。RedShapeDecorator 是 ShapeDecorator的扩展类,DecoratorPatternDemo则是对这个模式的测试类. UML类图如下所示。
定义Shape接口.
public interface Shape { void draw(); }Shape的子类Circle、Rectangle.
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"); } }
抽象装饰类ShapeDecorator。
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"); } }
测试类:
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(); } }
你会发现装饰模式与适配器模式有点像,但是适配器模式强调的是协调两个对象,而装饰模式则是添加新的功能给某个对象。