设计模式学习笔记——装饰模式
2017-04-13 20:42
330 查看
定义
装饰模式——动态地将责任附加到对象上。就增加功能来说,装饰模式相比生成子类更为灵活。使用场景
需要透明且动态地扩展类的功能时。需要去除相关类中重复的装饰逻辑时。
UML类图
Component:是定义的一个对象接口,可以给这些对象动态地添加职责。
ConcreteComponent:组件具体实现类。该类是Component类的基本实现,也是我们装饰的具体对象。
Decorator:装饰抽象类。其内部一定要有一个指向组件对象的引用。
ConcreteComponentA:具体的装饰者实现类。
例子
人的着装就是人的装饰,下面用小美着装打扮来演示装饰模式:人着装接口:
interface People { void dress(); }
小美:
public class XiaoMei implements People { private String name; public XiaoMei(String name) { this.name = name; } @Override public void dress() { System.out.print(name); } }
着装类:
public class Finery implements People { protected People people; public Finery(People people) { this.people = people; } @Override public void dress() { if (people != null) { people.dress(); } } }
具体着装类:
public class WhiteTShirt extends Finery { public WhiteTShirt(People people) { super(people); } @Override public void dress() { super.dress(); System.out.print(" 上身穿简单白T恤 "); } } public class Tights extends Finery { public Tights(People people) { super(people); } @Override public void dress() { super.dress(); System.out.print(" 下半身紧身小脚裤 "); } } public class NickShoes extends Finery { public NickShoes(People people) { super(people); } @Override public void dress() { super.dress(); System.out.print(" 脚穿Nike鞋 "); } }
客户端调用:
public class Test { public static void main(String[] args) { XiaoMei xiaoMei = new XiaoMei("小美"); WhiteTShirt wt = new WhiteTShirt(xiaoMei); Tights ts = new Tights(wt); NickShoes ns = new NickShoes(ts); ns.dress(); } }
输出结果:
小美 上身穿简单白T恤 下半身紧身小脚裤 脚穿Nike鞋
这只是一个简单的例子,你可以灵活的实现其他的具体着装类,在使用的时候替换。
总结
装饰模式的优点就是把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效地把类的核心职责和装饰功能区分开,而且可以有效的去除相关类中重复的装饰逻辑。本博文为读书笔记:
《Head First 设计模式》
《大话设计模式》
《Android源码设计模式解析与实战》
相关文章推荐
- 步步为营 .NET 设计模式学习笔记 十四、Decorator(装饰模式)
- java 设计模式 学习笔记(5) 装饰模式
- 黑马程序员_基础_IO流学习笔记_文本文件读取及复制、字符流的缓冲区和装饰设计模式
- 【设计模式学习笔记十】【结构型模式】【装饰模式(Decorator)】
- 设计模式学习笔记——装饰模式
- 设计模式学习笔记(2)之装饰模式(Decorator)
- 设计模式--装饰模式学习笔记
- 设计模式 学习笔记(3)装饰模式、代理模式
- java 设计模式学习笔记九 decorator装饰模式
- java 设计模式学习笔记九 decorator装饰模式
- 设计模式学习笔记-装饰模式
- Head First 设计模式学习笔记(3)---装饰器模式
- 设计模式学习笔记十五:装饰模式(Decorator Pattern)
- 步步为营 .NET 设计模式学习笔记 十四、Decorator(装饰模式)
- HeadFirst 设计模式学习笔记3--装饰模式
- 设计模式学习笔记(三)装饰模式(Decorator)
- 黑马程序员 java学习笔记3-IO流之字节流与装饰设计模式
- 设计模式学习笔记-装饰模式
- 基础_IO流学习笔记_文本文件读取及复制、字符流的缓冲区和装饰设计模式
- 步步为营 .NET 设计模式学习笔记 十四、Decorator(装饰模式)