设计模式——装饰器模式
设计模式——装饰器模式
一、概述
1、装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式。
2、装饰器模式的优点:动态给一个对象添加额外的功能,就增扩展共功能来说,装饰器模式比生成子类更灵活。(装饰模式是继承的一个替代模式)
3、缺点:多层装饰比较复杂
4、装饰器模式与建造者模式的区别:
- 前者是结构性设计模式,后者是创建型设计模式。
- 装饰器模式是扩展一个现有对象的功能。而建造者模式则是创建一个新的对象并赋予他相应的功能。
二、绘制UML类图
在Idea中使用PlantUML 插件绘制UML类图
@startuml abstract class Decorator{ # Shape decoratedShape + draw() } interface Shape{ + draw() } class Circle{ + draw() } class Rectangle{ + draw() } class RedBorder{ # Shape decoratedShape - setRedBorder() + draw() } class BlueFiller{ # Shape decoratedShape - setFiller() + draw() } Shape <|.. Decorator Shape <|.. Circle Shape <|.. Rectangle Decorator <|-- BlueFiller Decorator <|-- RedBorder @enduml

三、代码实现
目录结构:

1、Shape接口
public interface Shape { void draw(); }
2、Shape接口的具体实现类
public class Circle implements Shape { @Override public void draw() { System.out.println("形状: 圆形"); } }
public class Rectangle implements Shape { @Override public void draw() { System.out.println("形状: 矩形"); } }
3、定义抽象装饰器类
public abstract class Decorator implements Shape { protected Shape decoratedShape; public Decorator(Shape decoratedShape){ this.decoratedShape = decoratedShape; } public void draw(){ decoratedShape.draw(); } }
4、定义具体装饰类
public class RedBorder extends Decorator { public RedBorder(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { decoratedShape.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape) { System.out.println("边框颜色: 红色"); } }
public class BlueFiller extends Decorator { public BlueFiller(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { decoratedShape.draw(); setFiller(decoratedShape); } public void setFiller(Shape decoratedShape) { System.out.println("填充色: 蓝色"); } }
5、测试
public class DecoratorPatternDemo { public static void main(String[] args) { Decorator blueCircle = new RedBorder(new BlueFiller(new Circle())); blueCircle.draw(); } }
注意:如果只有一个ConcreateComponent1具体类,则直接让抽象装饰类继承ConcreateComponent1类,而不用再定义一个Component接口。
6、运行结果

四、参考链接
- 《大话设计模式》

浙公网安备 33010602011771号