一、一个叫声接口和几只鸭子 1、从一个叫声接口开始 {《HeadFirst设计模式》Delphi代码之模式小结 } { 一个叫声接口 } { 编译工具:Delphi2010 for win32 } { E-Mail :xshlife@163.com } unit uQuackable; interface type IQuackable = interface(IInterface) procedure Quack; end; implementation end. 2、几只鸭子实现了该叫声接口。 {《HeadFirst设计模式》Delphi代码之模式小结 } { 几只鸭子实现了声接口 } { 编译工具:Delphi2010 for win32 } { E-Mail :xshlife@163.com } unit uDuck; interface uses uQuackable; type TMallardDuck = class(TInterfacedObject, IQuackable) public procedure Quack; end; TRedHeadDuck = class(TInterfacedObject, IQuackable) public procedure Quack; end; TDuckCall = class(TInterfacedObject, IQuackable) public procedure Quack; end; TRubberDuck = class(TInterfacedObject, IQuackable) public procedure Quack; end; implementation { TMallardDuck } procedure TMallardDuck.Quack; begin Writeln('Quack'); end; { TRedHeadDuck } procedure TRedHeadDuck.Quack; begin Writeln('Quack'); end; { TDuckCall } procedure TDuckCall.Quack; begin Writeln('Kwak'); end; { TRubberDuck } procedure TRubberDuck.Quack; begin Writeln('Squeak'); end; end. 3、叫声接口为鸭鸣器提供服务。叫声接口与鸭鸣器的关系比与它的实现类更密切。 {《HeadFirst设计模式》Delphi代码之模式小结 } { 鸭鸣模拟器 } { 编译工具:Delphi2010 for win32 } { E-Mail :xshlife@163.com } unit uDuckSimulator; interface uses uQuackable, uDuck; type TDuckSimulator = class(TObject) private procedure Simulate(aDuck: IQuackable); overload; public procedure Simulate; overload; end; implementation { TDuckSimulator } procedure TDuckSimulator.Simulate(aDuck: IQuackable); { 此处交给多态处理 } begin aDuck.Quack; end; procedure TDuckSimulator.Simulate; var aMallardDuck: IQuackable; aRedHeadDuck: IQuackable; aDuckCall : IQuackable; aRubberDuck : IQuackable; begin try { 创建鸭鸣实例 } aMallardDuck := TMallardDuck.Create; aRedHeadDuck := TRedHeadDuck.Create; aDuckCall := TDuckCall.Create; aRubberDuck := TRubberDuck.Create; Writeln('Duck Simulator'); { 模拟鸭鸣 } Simulate(aMallardDuck); Simulate(aRedHeadDuck); Simulate(aDuckCall); Simulate(aRubberDuck ); finally aMallardDuck := nil; aRedHeadDuck := nil; aDuckCall := nil; aRubberDuck := nil; end; end; end. 4、客户端。 {《HeadFirst设计模式》Delphi代码之模式小结 } { 客户端 } { 编译工具:Delphi2010 for win32 } { E-Mail :xshlife@163.com } program pDuckSimulator; {$APPTYPE CONSOLE} uses uDuck in 'uDuck.pas', uDuckSimulator in 'uDuckSimulator.pas', uQuackable in 'uQuackable.pas'; var aSimulator: TDuckSimulator; begin aSimulator := TDuckSimulator.Create; aSimulator.Simulate; aSimulator.Free; Readln; end. 5、运行结果: