炒冷饭系列:设计模式 装饰模式
来源:互联网 发布:数据库监控 编辑:程序博客网 时间:2024/06/03 01:52
炒冷饭系列:设计模式 装饰模式
摘要: 原创出处: http://www.cnblogs.com/Alandre/ 泥沙砖瓦浆木匠 希望转载,保留摘要,谢谢!
钢琴弹得好是艺术,文章写的好也是艺术。
一、什么是装饰模式抽象工厂模式
二、装饰模式的结构 角色和职责
三、装饰模式实现
一、什么是抽象工厂模式
装饰( Decorator )模式又叫做包装模式。通 过一种对客户端透明的方式来扩展对象的功能, 是继承关系的一个替换方案。
二、装饰模式的结构 角色和职责
以下是对此图的见解,不服别喷。Component是实体接口 或者 抽象类。左边的ConcreteComponent是其实现(功能)。Decorator装饰,所谓的装饰抽象类就是把接口类实现,然后加上DoSomething的模块。
然后下面就是各个对具体装饰的实现,如果需要多功能结合 不是相互结合,而是通过父类抽象结合对象达到目的。具体可以参考下面案例的实现图解。
抽象组件角色: 一个抽象接口,是被装饰类和 装饰类的父接口。
具体组件角色:为抽象组件的实现类。
抽象装饰角色:包含一个组件的引用,并定义了 与抽象组件一致的接口。
具体装饰角色:为抽象装饰角色的实现类。负责 具体的装饰。
三、装饰模式实现
局部类图:
具体实现:
Car
public interface Car { public void show(); public void run();}
RunCar
public class RunCar implements Car { public void run() { System.out.println("可以跑"); } public void show() { this.run(); }}
CarDecorator
public abstract class CarDecorator implements Car{ private Car car; public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public CarDecorator(Car car) { this.car = car; } public abstract void show();}
上面相当于搭了好架子,后面需要具体实现了。
FlyCarDecorator
public class FlyCarDecorator extends CarDecorator{ public FlyCarDecorator(Car car) { super(car); } public void show() { this.getCar().show(); this.fly(); } public void fly() { System.out.println("可以飞"); } public void run() { }}
SwimCarDecorator
public class SwimCarDecorator extends CarDecorator { public SwimCarDecorator(Car car) { super(car); } public void show() { this.getCar().show(); this.swim(); } public void swim() { System.out.println("可以游"); } public void run() { }}
然后测试代码
MainClass
public class MainClass { public static void main(String[] args) { Car car = new RunCar(); car.show(); System.out.println("---------"); Car swimcar = new SwimCarDecorator(car); swimcar.show(); System.out.println("---------"); Car flySwimCar = new FlyCarDecorator(swimcar); flySwimCar.show(); }}
运行可以得到以下结果:
可以跑---------可以跑可以游---------可以跑可以游可以飞
四、感谢知识来源和小结
一、什么是装饰模式抽象工厂模式
二、装饰模式的结构 角色和职责
三、装饰模式实现
来自:java设计模式
如以上文章或链接对你有帮助的话,别忘了在文章按钮或到页面右下角点击 “赞一个” 按钮哦。你也可以点击页面右边“分享”悬浮按钮哦,让更多的人阅读这篇文章。
书法是心领神会的艺术
鄙人书法欣赏:
- 炒冷饭系列:设计模式 装饰模式
- 炒冷饭系列:设计模式 工厂模式
- 炒冷饭系列:设计模式 工厂方法模式
- 炒冷饭系列:设计模式 抽象工厂模式
- 炒冷饭系列:设计模式 单例模式
- 炒冷饭系列:设计模式 原型模式
- 炒冷饭系列:设计模式 建造者模式
- 设计模式系列-装饰模式
- 装饰模式----设计模式系列
- JAVA系列-设计模式-装饰者模式
- 设计模式系列——装饰模式
- 设计模式系列-----------装饰器模式(Decorator)
- 设计模式系列:装饰者模式
- 设计模式实现系列-策略模式-装饰模式-代理模式
- PHP设计模式系列 - 装饰器
- PHP设计模式系列 - 装饰器
- PHP设计模式系列 - 装饰器
- 设计模式---装饰模式
- Windows Shell 右键菜单 编译错误处理
- 解析10053事件(转)
- 大是大厦大厦大方方的是
- Rails API:accepts_nested_attributes_for
- 1408100909-ny-会场安排问题
- 炒冷饭系列:设计模式 装饰模式
- 大是大厦大厦大方方的是
- 大是大厦大厦大方方的是
- quantz入门和使用流程(转载)
- UVA 439 - Knight Moves
- poj1861
- HDU 2222——Keywords Search(AC自动机)
- eclipse上android开发如何调用C++代码--初尝试
- C语言中realloc 使用详解(转)