您的位置:首页 > 编程语言 > Delphi

Delphi 里的接口聚合的写法。俺自己写的测试例子代码

2017-04-06 10:07 477 查看
unit Unit1;

{-----------------------------------------------------------------------------

本程序演示接口委托聚合:

TMyClass 拥有并实现了 IMyTask 接口

TMyPlan 类拥有 IMyTask 接口,但没有去实现这个接口里的 SayHell 方法,而是通过

property MyTask: IMyTask read FMyClass implements IMyTask; 语句,将这个实现委托给内部的 FMyClass 接口实现。

传统的面向类的代码,当做一个包装类,包装多个子类在里面的时候,要在包装类的 public 里

再实现一次子类里的方法,在实现的方法里再调用子类的方法。这种办法也有人称为【委托】。

如果采用接口委托,则不用重复写代码,直接写一句:

property MyTask: IMyTask read FMyClass implements IMyTask; 则包装类

就不用在 public 里再次重复实现一次接口里的函数方法等等了。这种办法也有人称为【聚合】

以下代码测试通过。

pcplayer 2011-10-23 星期日。

-----------------------------------------------------------------------------}

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls;

type

IMyTask = Interface

['{1B9D204E-1662-4280-A8E6-D7F518A425F5}']

function SayHello: string;

End;

TMyClass = class(TInterfacedObject, IMyTask)

private

public

function SayHello: string;

end;

TMyPlan = class(TInterfacedObject, IMyTask)

private

FMyClass: IMyTask;

public

constructor Create;

property MyTask: IMyTask read FMyClass implements IMyTask;

end;

TForm1 = class(TForm)

Button1: TButton;

Label1: TLabel;

procedure Button1Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Form1: TForm1;

implementation

{$R *.dfm}

{ TMyClass }

function TMyClass.SayHello: string;

begin

Result := 'Hello';

end;

{ TMyPlan }

constructor TMyPlan.Create;

begin

inherited;

FMyClass := TMyClass.Create as IMyTask;

end;

procedure TForm1.Button1Click(Sender: TObject);

var

MyPlan: IMyTask;

begin

MyPlan := TMyPlan.Create;

Label1.Caption := MyPlan.SayHello;

MyPlan := nil;

end;

end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: