《大话设计模式》——第六、七章 装饰模式 代理模式
第六章 装饰模式
Main
1 package 2 { 3 import flash.display.Sprite; 4 5 public class Main extends Sprite 6 { 7 public function Main() 8 { 9 var c:ConcreteComponent = new ConcreteComponent(); 10 var d1:ConcreteDecoratorA = new ConcreteDecoratorA(); 11 var d2:ConcreteDecoratorB = new ConcreteDecoratorB(); 12 13 d1.SetComponent(c); 14 d2.SetComponent(d1); 15 d2.Operation(); 16 } 17 } 18 }
Component
1 package{ 2 public class Component { 3 public function Operation():void{ 4 5 } 6 } 7 }
ConcreteComponent
1 package{ 2 public class ConcreteComponent extends Component{ 3 public override function Operation():void{ 4 trace("具体对象的操作"); 5 } 6 } 7 }
Decorator
1 package{ 2 public class Decorator extends Component{ 3 protected var component:Component; 4 5 public function SetComponent(component:Component):void{ 6 this.component = component; 7 } 8 public override function Operation():void{ 9 if(component != null){ 10 component.Operation(); 11 } 12 } 13 } 14 }
ConcreteDecoratorA
1 package{ 2 public class ConcreteDecoratorA extends Decorator{ 3 private var addedState:String; 4 5 public override function Operation():void{ 6 super.Operation(); 7 addedState = "New State"; 8 trace("具体装饰对象A的操作"); 9 } 10 } 11 }
ConcreteDecoratorB
1 package{ 2 public class ConcreteDecoratorB extends Decorator{ 3 public override function Operation():void{ 4 super.Operation(); 5 addedBehavior(); 6 trace("具体装饰对象B的操作"); 7 } 8 private function addedBehavior():void{ 9 10 } 11 } 12 }
第七章 代理模式
Main
1 package 2 { 3 import flash.display.Sprite; 4 5 public class Main extends Sprite 6 { 7 public function Main() 8 { 9 var jiaojiao:SchoolGirl = new SchoolGirl(); 10 jiaojiao.name = "李娇娇"; 11 12 var daili:Proxy = new Proxy(jiaojiao); 13 daili.GiveDolls(); 14 } 15 } 16 }
IGiveGift
1 package 2 { 3 public interface IGiveGift 4 { 5 function GiveDolls():void; 6 } 7 }
Pursuit
1 package{ 2 public class Pursuit implements IGiveGift{ 3 private var mm:SchoolGirl; 4 public function Pursuit(mm:SchoolGirl){ 5 this.mm = mm; 6 } 7 public function GiveDolls():void{ 8 trace(mm.name + "送你洋娃娃"); 9 } 10 } 11 }
SchoolGirl
1 package{ 2 public class SchoolGirl { 3 private var _name:String; 4 public function SchoolGirl(){ 5 6 } 7 public function get name():String{ 8 return _name; 9 } 10 public function set name(value:String):void{ 11 _name = value; 12 } 13 14 } 15 }
Proxy
1 package{ 2 public class Proxy implements IGiveGift{ 3 private var gg:Pursuit; 4 public function Proxy(mm:SchoolGirl){ 5 gg = new Pursuit(mm); 6 } 7 public function GiveDolls():void{ 8 gg.GiveDolls(); 9 } 10 } 11 }