我倒是会直接用interface实现聚合
IMyInterface=interface
['{2E173B2D-6BE9-4519-8E5F-6DEF400335EC}']
function SayHello:string;
end;
IMyInterface2=interface
['{3FD6CFDF-E028-4FD6-9834-299404C15FFF}']
function SayHello2:string;
end;
TMyObject2=class(TInterfacedObject,IMyInterface2)
function SayHello2:string;
end;
TMyObject=class(TInterfacedObject,IMyInterface,IMyInterface2)
private
FDelgateObj:IMyInterface2;
public
property DelgateObj:IMyInterface2 read FDelgateObj write FDelgateObj implements IMyInterface2;
constructor Create;
function SayHello:string;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TMyObject.Create;
begin
FDelgateObj:=Nil;
end;
function TMyObject2.SayHello2:string;
begin
Result:='I am Object2';
end;
function TMyObject.SayHello:string;
begin
Result:='I am Object1';
end;
procedure TForm1.Button1Click(Sender: TObject);
var
MyObject:TMyObject;
MyObject2:TMyObject2;
Intf1:IMyInterface;
Intf2:IMyInterface2;
begin
MyObject:=TMyObject.Create;
MyObject.FDelgateObj:=TMyObject2.Create;
if Supports(MyObject,IMyInterface,Intf1) then
ShowMessage(Intf1.SayHello);
if Supports(MyObject,IMyInterface2,Intf2) then
ShowMessage(Intf2.SayHello2);
end;