05.Delphi接口的多重继承深入

由于是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.

 

转载于:https://www.cnblogs.com/tianpan2019/p/11477546.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值