设计模式之装饰模式 Decoratory Pattern java
来源:互联网 发布:jquery解析json数组 编辑:程序博客网 时间:2024/06/05 14:27
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。(GOF《设计模式》)。
java的拦截器就是装饰模式和代理模式的很好运用。假定有人(IPerson)接口,给接口提供eat()行为,即每个人都要吃饭。然而现代人(Modern)可能在吃饭前要洗手(washHand),吃饭后要散步(walk);然而古代人(Ancients)可能是饭前拜神(worship),饭后舞蹈(dance)。这时我们发现同样是吃饭而饭前饭后则不经相同。我们可以使用继承来解决这样问题,然而继承带来的代价是子类的迅速膨胀,还有就是因为饭前和饭后的行为是不确定的,使用继承实现起来将变得十分困难。使用装饰模式将简化这一实现。
2) IPerson.java
package org.dql.model;
public interface IPerson {
public void eat();
}
3) Decorator.java
package org.dql.model;
public class Decorator implements IPerson{
private IPerson m_Person;
public Decorator(IPerson person)
{
m_Person = person;
}
@Override
public void eat() {
m_Person.eat();
}
}
4) Modern.java
package org.dql.model;
public class Modern extends Decorator {
public Modern(IPerson person) {
super(person);
}
private void washHands() {
System.out.println("洗手。。。。。");
}
private void walk() {
System.out.println("散步。。。。。");
}
public void eat() {
washHands();
super.eat();
walk();
}
}
5) Ancients.java
package org.dql.model;
public class Ancients extends Decorator {
private void worship()
{
System.out.println("朝拜神灵。。。。。");
}
private void dance()
{
System.out.println("舞蹈。。。。。");
}
public Ancients(IPerson person) {
super(person);
}
@Override
public void eat() {
worship();
super.eat();
dance();
}
}
6) 测试Program.java
package org.dql.model;
public class Program {
public static void main(String[] args) {
IPerson person=new Person();
Decorator newperson=new Modern(person);
System.out.println("*********现代人吃饭***********");
newperson.eat();
Decorator ancients=new Ancients(person);
System.out.println("/n*********古代人吃饭***********");
ancients.eat();
}
}
7) 运行结果
*********现代人吃饭***********
洗手。。。。。
吃饭。。。。
散步。。。。。
*********古代人吃饭***********
朝拜神灵。。。。。
吃饭。。。。
舞蹈。。。。。
- 设计模式之装饰模式 Decoratory Pattern java
- JAVA设计模式之 装饰模式【Decorator Pattern】
- Java设计模式之装饰者模式(Decorator pattern)
- 设计模式之装饰模式(Decorator Pattern)
- 设计模式之装饰模式--- Pattern Decorator
- Java之装饰模式(Decorator Pattern)
- Java之装饰模式(Decorator Pattern)
- Java之装饰模式(Decorator Pattern)
- Java设计模式之装饰设计模式
- 设计模式系列之四:装饰者模式(Decorator Pattern)
- 设计模式笔记之装饰者模式(Decorator Pattern)
- 设计模式之装饰者模式Decorator Pattern
- 设计模式(二)之装饰模式(Decorator Pattern)
- C#设计模式之装饰者模式(Decorator Pattern)
- 设计模式之装饰模式(Decorate Pattern)
- 设计模式(结构型)之装饰者模式(Decorator Pattern)
- 设计模式总结之Decorator Pattern(装饰者模式)
- C#设计模式之装饰模式(Decorator Pattern)
- 常用数据类型使用转换详解
- 提高网页打开速度的一些小技巧
- 疯狂的程序员48
- File Encryption and Decryption in C#
- using的用法
- 设计模式之装饰模式 Decoratory Pattern java
- 如何得到本进程的CPU占用率?
- 補全未出勤日期
- 如何获取 Exception 的 HResult 值
- VS 2008 下载地址
- GridView导出到Excel或Word文件
- 用Netbeans6创建Web Service
- CFile打开文件模式总结
- 水晶报表问题汇总(水晶报表的使用与查询条件生成报表、注册码、打印问题、模式使用示例、C#.Net的WinForm中的使用、程序发布与部署)