二、加入适配器模式
1、鹅也要加入鸭鸣模拟器
代码
1 {《HeadFirst设计模式》Delphi代码之模式小结 } 2 { 加入适配器模式 } 3 { 编译工具:Delphi2010 for win32 } 4 { E-Mail :[email protected] } 5 6 unit uGoose; 7 8 interface 9 10 type 11 TGoose = class(TObject) 12 public 13 procedure Honk; 14 end; 15 16 implementation 17 18 { TGoose } 19 20 procedure TGoose.Honk; 21 begin 22 Writeln('Honk'); 23 end; 24 25 end.
2、但鹅的叫声接口与鸭子的不一致,鹅变量的类型与procedure Simulate(aDuck: IQuackable)要求的不一致。加入适配器转换鹅的接口,同时也保持了procedure Simulate(aDuck: IQuackable)对多态的要求。
代码
1 {《HeadFirst设计模式》Delphi代码之模式小结 } 2 { 加入适配器模式 } 3 { 编译工具:Delphi2010 for win32 } 4 { E-Mail :[email protected] } 5 6 unit uGooseAdapter; 7 8 interface 9 10 uses 11 uQuackable, uGoose; 12 13 type 14 TGooseAdapter = class(TInterfacedObject, IQuackable) 15 private 16 FGoose: TGoose; 17 public 18 constructor Create(aGoose: TGoose); 19 destructor Destroy; override; 20 procedure Quack; 21 end; 22 23 implementation 24 25 { TGooseAdapter } 26 27 constructor TGooseAdapter.Create(aGoose: TGoose); 28 begin 29 FGoose := aGoose; 30 end; 31 32 destructor TGooseAdapter.Destroy; 33 begin 34 FGoose.Free; 35 inherited Destroy; 36 end; 37 38 procedure TGooseAdapter.Quack; 39 begin 40 FGoose.Honk; 41 end; 42 43 end.
3、最后测试一下
代码
1 {《HeadFirst设计模式》Delphi代码之模式小结 } 2 { 测试 } 3 { 编译工具:Delphi2010 for win32 } 4 { E-Mail :[email protected] } 5 6 unit uDuckSimulator; 7 8 interface 9 10 uses 11 uQuackable, uDuck, uGoose, uGooseAdapter; 12 13 type 14 TDuckSimulator = class(TObject) 15 private 16 procedure Simulate(aDuck: IQuackable); overload; 17 public 18 procedure Simulate; overload; 19 end; 20 21 implementation 22 23 { TDuckSimulator } 24 25 procedure TDuckSimulator.Simulate(aDuck: IQuackable); 26 begin 27 aDuck.Quack; 28 end; 29 30 procedure TDuckSimulator.Simulate; 31 var 32 aMallardDuck: IQuackable; 33 aRedHeadDuck: IQuackable; 34 aDuckCall : IQuackable; 35 aRubberDuck : IQuackable; 36 aGooseDuck : IQuackable; 37 begin 38 try 39 aMallardDuck := TMallardDuck.Create; 40 aRedHeadDuck := TRedHeadDuck.Create; 41 aDuckCall := TDuckCall.Create; 42 aRubberDuck := TRubberDuck.Create; 43 aGooseDuck := TGooseAdapter.Create(TGoose.Create); 44 45 Writeln('Duck Simulator: With Goose Adapter'); 46 47 Simulate(aMallardDuck); 48 Simulate(aRedHeadDuck); 49 Simulate(aDuckCall); 50 Simulate(aRubberDuck); 51 Simulate(aGooseDuck ); 52 finally 53 aMallardDuck := nil; 54 aRedHeadDuck := nil; 55 aDuckCall := nil; 56 aRubberDuck := nil; 57 aGooseDuck := nil; 58 end; 59 end; 60 61 end.
代码
1 {《HeadFirst设计模式》Delphi代码之模式小结 } 2 { 客户端 } 3 { 编译工具:Delphi2010 for win32 } 4 { E-Mail :[email protected] } 5 6 program pDuckSimulator; 7 8 {$APPTYPE CONSOLE} 9 10 uses 11 uQuackable in 'uQuackable.pas', 12 uDuck in 'uDuck.pas', 13 uDuckSimulator in 'uDuckSimulator.pas', 14 uGooseAdapter in 'uGooseAdapter.pas', 15 uGoose in 'uGoose.pas'; 16 17 var 18 aSimulator: TDuckSimulator; 19 20 begin 21 aSimulator := TDuckSimulator.Create; 22 23 aSimulator.Simulate; 24 25 aSimulator.Free; 26 27 Readln; 28 end.
4、运行结果:
|
请发表评论