【设计模式】9、装饰器模式
2016-02-25 11:33
239 查看
package com.shejimoshi.structural.Decorator; /** * 功能:这个是我们装饰器的基类,用来生成被装饰类和装饰器类 * 时间:2016年2月25日上午10:05:37 * 作者:cutter_point */ public abstract class Component { //这个方法就是我们装饰器要进行装饰的操作 public abstract void tuo(); }
package com.shejimoshi.structural.Decorator; /** * 功能:动态地给一个对象添加一些额外的职责。就增加功能来说装饰器模式比生成子类更加灵活 * 装饰器就是用装饰器类来对我们的私有成员(装饰对象)进行相应的扩展功能 * 适用:在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责 * 处理那些可以撤销的职责 * 时间:2016年2月25日上午9:45:43 * 作者:cutter_point */ public class Person extends Component { private String name; public Person(String name) { this.name = name; } @Override public void tuo() { System.out.print(this.name + "准备上床睡觉\t"); } }
package com.shejimoshi.structural.Decorator; /** * 功能:装饰器基类,用来对相应的对象进行装饰 * 时间:2016年2月25日上午10:15:02 * 作者:cutter_point */ public abstract class Decorator extends Component { protected Component component; public Decorator(Component component) { this.component = component; } @Override public void tuo() { if(component != null) component.tuo(); } }
package com.shejimoshi.structural.Decorator; /** * 功能:对于一个操作,上衣 * 时间:2016年2月25日上午10:18:28 * 作者:cutter_point */ public class Shangyi extends Decorator { //构造函数 public Shangyi(Component component) { super(component); } @Override public void tuo() { super.tuo(); System.out.print("脱上衣\t"); } }
package com.shejimoshi.structural.Decorator; /** * 功能:对应裤子操作 * 时间:2016年2月25日上午10:49:03 * 作者:cutter_point */ public class Kuzhi extends Decorator { public Kuzhi(Component component) { super(component); } @Override public void tuo() { super.tuo(); System.out.print("脱掉裤子\t"); } }
package com.shejimoshi.structural.Decorator; /** * 功能:装饰器模式 * 时间:2016年2月25日上午11:13:55 * 作者:cutter_point */ public class Test { public static void main(String[] args) { Component person = new Person("cutter_point"); Decorator shangyi = new Shangyi(person); shangyi.tuo(); System.out.println(); Decorator kuzhi = new Kuzhi(person); kuzhi.tuo(); } }
测试结果:
cutter_point准备上床睡觉 脱上衣 cutter_point准备上床睡觉 脱掉裤子
相关文章推荐
- IOS 关键字self,super,copy, retain, assign , readonly , readwrite, nonatomic、@synthesize、@property、@dynamic
- 日志切割
- 欢迎使用CSDN-markdown编辑器
- STL 疑问
- Codeforces 617E XOR and Favorite Number (区间异或和 莫队算法 分块暴力)
- Boyer-Moore Majority Vote Algorithm的更一般性问题
- 常用宏定义
- 关联分析的FP-growth算法 in Python
- 通过汇编一个简单的C程序,分析汇编代码理解计算机是如何工作的
- Git push 常见erro解决办法
- java 网络编程基础 1
- 1036: [ZJOI2008]树的统计Count
- 一条scan查询把HBase集群干趴下
- Android中如何控制元素的显示隐藏?
- javascript限制和统计文本输入字数的解决方案
- 静态文件过期时间
- Android代码优化小技巧
- android贝塞尔曲线的简单应用
- 初学Redis——用Redis作为Mysql数据库的缓存 (2)
- 如何将IE浏览器设置为调试.jsp等代码的工具