由于是IInterface,申明了SayHello,需要由继承类来实现函数,相对于03篇可以再精简一下
unit uSayHello; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs; type // 说话类,由于是IInterface,申明了SayHello,需要由继承类来实现函数 ISpeakLanguage = interface(IInterface) function SayHello: string; end; ISpeakChinese = interface(ISpeakLanguage) end; ISpeakEnglish = interface(ISpeakLanguage) end; // TInterfacedObject相对于IInterface,添加了一些属性,更方便好用 TMan = class(TInterfacedObject) private FName: string; public // 名字 property Name: string read FName write FName; end; TChinese = class(TMan, ISpeakChinese) private function SayHello: string; end; TAmerican = class(TMan, ISpeakEnglish) private function SayHello: string; end; TAmericanChinese = class(TMan, ISpeakChinese, ISpeakEnglish) public constructor create; function SayHello: string; end; implementation function TAmerican.SayHello: string; begin result := 'Hello!'; end; function TChinese.SayHello: string; begin result := '你好!'; end; constructor TAmericanChinese.create; begin name := 'Tom Wang'; end; // 继承中文和英文 function TAmericanChinese.SayHello: string; var Dad: ISpeakChinese; Mum: ISpeakEnglish; begin Dad := TChinese.create; Mum := TAmerican.create; // 输出 result := Dad.SayHello + Mum.SayHello; end; end.
界面代码如下
unit frmMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Button1: TButton; LabeledEdit1: TLabeledEdit; procedure Button1Click(Sender: TObject); private {Private declarations} public {Public declarations} end; var Form1: TForm1; implementation uses uSayHello; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var Tom: TAmericanChinese; begin Tom := TAmericanChinese.Create; try LabeledEdit1.text := Tom.Name; // 输出 Showmessage(Tom.sayhello); finally Tom.Free; end; end; end.