被装饰的组件,Beverage是抽象类(as3不支持抽象类)
package {
//Beverage是抽象类,不要直接new Beverage
public class Beverage {
protected var _price:Number;
protected var _description:String;
public function Beverage() {
}
public function get price():Number {
return _price;
}
public function get description():String {
return _description;
}
}
}
装饰者,Decorator是抽象类
package
{
public class Decorator extends Beverage {
public function Decorator() {
}
override public function get price():Number {
return 0;
}
override public function get description():String {
return "";
}
}
}
具体的被装饰组件
package {
public class Coffee extends Beverage {
public function Coffee() {
_price = 50.5;
}
override public function get description():String {
return "[咖啡]";
}
}
}
具体的装饰者
package {
public class Sugar extends Decorator {
private var beverage:Beverage;
public function Sugar(b:Beverage) {
beverage = b;
}
override public function get price():Number {
return beverage.price + 0.5;
}
override public function get description():String {
return beverage.description + "[糖]";
}
}
}
具体的装饰者
package {
public class Milk extends Decorator {
private var beverage:Beverage;
public function Milk(b:Beverage) {
beverage = b;
}
override public function get price():Number {
return beverage.price + 2.5;
}
override public function get description():String {
return beverage.description + "[牛奶]";
}
}
}
测试类
package {
import flash.display.Sprite;
public class DecoratorTest extends Sprite{
private var beverage:Beverage;
public function DecoratorTest() {
beverage = new Coffee();
beverage = new Sugar(beverage);
beverage = new Sugar(beverage);
beverage = new Milk(beverage);
trace(beverage.description);
trace("price: " + beverage.price);
}
}
}