Delphi 接口托管实现

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses
 6   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 7   Dialogs, StdCtrls;
 8 
 9 type
10   TForm1 = class(TForm)
11     Button1: TButton;
12     procedure Button1Click(Sender: TObject);
13   private
14     { Private declarations }
15   public
16     { Public declarations }
17   end;
18 
19   IMyInterface = interface(IUnknown)
20    procedure ShowString(s: string);
21   end;
22 
23   TMyClass = class(TInterfacedObject, IMyInterface)
24   public
25     procedure ShowString(s: string);
26   end;
27 
28   TSecondClass = class(TInterfacedObject, IMyInterface)
29   protected
30     myInterface: IMyInterface;
31   protected
32     property my: IMyInterface read myInterface implements IMyInterface;
33   public
34     constructor Create(AOwner: TObject); overload;
35   end;
36 
37 
38 var
39   Form1: TForm1;
40 
41 implementation
42 
43 {$R *.dfm}
44 
45 procedure TForm1.Button1Click(Sender: TObject);
46 var
47   myclass: TMyClass;
48   mySecondclass: TSecondClass;
49 begin
50   myclass := TMyClass.Create;
51   mySecondclass := TSecondClass.Create(nil);
52   myclass.ShowString('sss');
53   mySecondclass.my.ShowString('aaa');
54   myclass.Free;
55   mySecondclass.Free;
56 end;
57 
58 { TMyClass }
59 
60 procedure TMyClass.ShowString(s: string);
61 begin
62   ShowMessage(s);
63 end;
64 
65 { TSecondClass }
66 
67 constructor TSecondClass.Create(AOwner: TObject);
68 begin
69   myInterface := TMyClass.Create;
70 end;
71 
72 end.
原文地址:https://www.cnblogs.com/devinblog/p/4692788.html