基本概念
装饰模式,动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比使用子类继承父类更为灵活,装饰模式可以有效地把类的核心职责和附加功能区分开。
结构图
上图摘自《大话设计模式》
应用场景
当需要往旧的类中添加新的方法或新的逻辑的时候,如果在主类中添加,会增加主类的复杂度;这些需要加入的东西如果仅仅是为了满足某些特定行为的需要,可以作为装饰功能来添加,从而使用装饰模式,使主类不变,仅负责核心职责的实现。
源码示例(以绘制图形作为主类核心职责,以添加边框颜色作为装饰功能)
1.创建Shape接口
package com.spook.decorator; /** * Shape接口 */ public interface Shape { public void draw(); }2.创建Circle类
package com.spook.decorator; /** * Circle类 */ public class Circle implements Shape { @Override public void draw() { // TODO Auto-generated method stub System.out.println("draw circle"); } }3.创建Square类
package com.spook.decorator; /** * Square类 */ public class Square implements Shape { @Override public void draw() { // TODO Auto-generated method stub System.out.println("draw square"); } }4.装饰者抽象类,实现Shape接口
package com.spook.decorator; /** * 装饰者抽象类 */ public abstract class ShapeDecorator implements Shape { protected Shape decoratedShape; public ShapeDecorator(Shape shape) { this.decoratedShape = shape; } @Override public void draw() { // TODO Auto-generated method stub if (decoratedShape != null) { decoratedShape.draw(); } } }5.蓝色边框装饰功能实现类
package com.spook.decorator; /** * 蓝色边框装饰者类 */ public class BlueShapeDecorator extends ShapeDecorator { public BlueShapeDecorator(Shape shape) { super(shape); // TODO Auto-generated constructor stub } @Override public void draw() { // TODO Auto-generated method stub super.draw(); setBlueBorder(decoratedShape); } private void setBlueBorder(Shape decoratedShape) { System.out.println("Border Color: Blue"); } }6.红色边框装饰功能实现类
package com.spook.decorator; /** * 红色边框装饰者类 */ public class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape shape) { super(shape); // TODO Auto-generated constructor stub } @Override public void draw() { // TODO Auto-generated method stub super.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape) { System.out.println("Border Color: Red"); } }7.测试类
package com.spook.decorator; /** * 测试类 */ public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Shape blueCircle = new BlueShapeDecorator(new Circle()); blueCircle.draw(); Shape redSquare = new RedShapeDecorator(new Square()); redSquare.draw(); } }运行测试类输出如下内容:
draw circle Border Color: Blue draw square Border Color: Red