当前位置 : 主页 > 编程语言 > delphi >

04.Delphi通过接口IInterface实现多重继承

来源:互联网 收集:自由互联 发布时间:2021-06-23
IInterface表示申明了一些函数,自己本身没有实现部分,需要由继承它的类来实现函数 uSayHello代码如下 unit uSayHello; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs;

IInterface表示申明了一些函数,自己本身没有实现部分,需要由继承它的类来实现函数

uSayHello代码如下

unit uSayHello;

interface

uses
  SysUtils,
  Windows,
  Messages,
  Classes,
  Graphics,
  Controls,
  Forms,
  Dialogs;

type
  // IInterface表示申明了一些函数,自己本身没有实现部分,需要由继承它的类来实现函数
  ISpeakChinese = interface(IInterface)
    function SayHello: string;
  end;

  // IInterface表示申明了一些函数,自己本身没有实现部分,需要由继承它的类来实现函数
  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
    // ISpeakChinese中定义的函数,序号在继承类中实现
    function SayHello: string;
  end;

  TAmerican = class(TMan, ISpeakEnglish)
  private
    // ISpeakChinese中定义的函数,序号在继承类中实现
    function SayHello: string;
  end;

  // 美籍华人 ,继承了人类,汉语和英语
  TAmericanChinese = class(TMan, ISpeakChinese, ISpeakEnglish)
  public
    constructor create;
    // ISpeakChinese中定义的函数,序号在继承类中实现
    function SayHello: string;
  end;

implementation

{
  ********************************** TAmerican ***********************************
}
function TAmerican.SayHello: string;
begin
  result := Hello!;
end;

{
  *********************************** TChinese ***********************************
}
function TChinese.SayHello: string;
begin
  result := 你好!;
end;

{
  ******************************* TAmericanChinese *******************************
}
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.
网友评论