uSayHello代码如下
unit uSayHello;
interface
uses
SysUtils,
Windows,
Messages,
Classes,
Graphics,
Controls,
Forms,
Dialogs;
type
ISpeakChinese = interface(IInterface)
function SayHello: string;
end;
ISpeakEnglish = interface(IInterface)
function SayHello: string;
end;
TMan = class(TInterfacedObject)
private
FName: string;
public
property Name: string read FName write FName;
end;
TChinese = class(TMan, ISpeakChinese)
private
FSkinColor: string;
function SayHello: string;
public
constructor create;
property SkinColor: string read FSkinColor write FSkinColor;
end;
TAmerican = class(TMan, ISpeakEnglish)
private
function SayHello: string;
end;
TAmericanChinese = class(TChinese, ISpeakEnglish)
public
constructor create;
function TomSayHello: string;
end;
implementation
function TAmerican.SayHello: string;
begin
result := 'Hello!';
end;
constructor TChinese.create;
begin
SkinColor := '黄色';
end;
function TChinese.SayHello: string;
begin
result := '你好!';
end;
constructor TAmericanChinese.create;
begin
name := 'Tom Wang';
Inherited;
end;
function TAmericanChinese.TomSayHello: string;
var
// Dad: ISpeakChinese;
Mum: ISpeakEnglish;
begin
// Dad:=TChinese.Create;
// 只有子类TAmerican才具体实现了SayHello的方法
Mum := TAmerican.create;
// SayHello是继承的中国人的Hello方法
result := 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;
LabeledEdit2: 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;
LabeledEdit2.text:=Tom.SkinColor;
Showmessage(Tom.Tomsayhello);
finally
Tom.Free;
end;
end;
end.
手机扫一扫
移动阅读更方便
你可能感兴趣的文章