您的位置:首页 > 编程语言 > Java开发

Java设计模式(9) 装饰器

2016-12-28 00:00 369 查看
/**
* 设计模式(9)
* 装饰器模式
*
* 和适配器模式基本相同,在不修改原始类的情况下修改功能
* 不同点是装饰器是扩展功能
*
*/

// 狗的接口
interface Dog {
void run();
}

// 狗的实现类
//
class NormalDog implements Dog {
public void run() {
System.out.println("dog.run");
}
}

//
// 简单的装饰器类
class FlyDog implements Dog {
Dog dog;

public FlyDog(Dog dog) {
this.dog = dog;
}

@Override
public void run() {
this.dog.run();
System.out.println("it can fly");
}
}

// 测试
// Test Decorator  Pattern
public class main {
public static void main(String[] argv) {
Dog flydog = new FlyDog(new NormalDog());
flydog.run();
}
}

/*
输出:
dog.run
it can fly
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: