《JAVA与模式》第9天―装饰模式 (三)

2014-11-24 08:24:27 · 作者: · 浏览: 2
09:30:11
*
* @类说明 :具体装饰角色“鸟儿”
*/
public class Bird extends Change {

public Bird(TheGreatestSage sage) {
super(sage);
}

@Override
public void move() {
// 代码
System.out.println("Bird Move");
}
}
 客户端类

[java]
package com.bankht.Decorator.wukong;

/**
* @author: 特种兵—AK47
* @创建时间:2012-6-26 上午09:30:32
*
* @类说明 :客户端类
*/
public class Client {

public static void main(String[] args) {
TheGreatestSage sage = new Monkey();
// 第一种写法
TheGreatestSage bird = new Bird(sage);
TheGreatestSage fish = new Fish(bird);
// 第二种写法
// TheGreatestSage fish = new Fish(new Bird(sage));
fish.move();
bird.move();
}

}
package com.bankht.Decorator.wukong;

/**
* @author: 特种兵—AK47
* @创建时间:2012-6-26 上午09:30:32
*
* @类说明 :客户端类
*/
public class Client {

public static void main(String[] args) {
TheGreatestSage sage = new Monkey();
// 第一种写法
TheGreatestSage bird = new Bird(sage);
TheGreatestSage fish = new Fish(bird);
// 第二种写法
// TheGreatestSage fish = new Fish(new Bird(sage));
fish.move();
bird.move();
}

}

  “大圣本尊”是ConcreteComponent类,而“鸟儿”、“鱼儿”是装饰类。要装饰的是“大圣本尊”,也即“猢狲”实例。

  上面的例子中,系统把大圣从一只猢狲装饰成了一只鸟儿(把鸟儿的功能加到了猢狲身上),然后又把鸟儿装饰成了一条鱼儿(把鱼儿的功能加到了猢狲+鸟儿身上,得到了猢狲+鸟儿+鱼儿)。

\

  如上图所示,大圣的变化首先将鸟儿的功能附加到了猢狲身上,然后又将鱼儿的功能附加到猢狲+鸟儿身上。

  

作者:m13666368773