代碼文件:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
end;
IMyInterface = interface
procedure Proc;
end;
TMyClass = class(TInterfacedObject, IMyInterface)
public
constructor Create;
destructor Destroy; override;
procedure Proc;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TMyClass.Create;
begin
inherited;
ShowMessage('TMyClass.Create');
end;
destructor TMyClass.Destroy;
begin
ShowMessage('TMyClass.Destroy');
inherited;
end;
procedure TMyClass.Proc;
begin
ShowMessage('IMyInterface.Proc');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
c: TMyClass;
begin
c := TMyClass.Create;
c.Proc;
c.Free;
ShowMessage('**********');
{將依次顯示:
TMyClass.Create
IMyInterface.Proc
TMyClass.Destroy
**********
}
end;
procedure TForm1.Button2Click(Sender: TObject);
var
i: IMyInterface;
begin
i := TMyClass.Create;
i.Proc;
ShowMessage('**********');
//在本段程序的最後, 編譯器能判斷出接口不再有用, 會釋放掉擁有它的類
{將依次顯示:
TMyClass.Create
IMyInterface.Proc
**********
TMyClass.Destroy
}
end;
procedure TForm1.Button3Click(Sender: TObject);
var
c: TMyClass;
i: IMyInterface;
begin
c := TMyClass.Create;
i := c;
//i := IMyInterface(c); {也可以這樣轉換}
//i := c as IMyInterface; {暫時不能使用 as, 接口擁有 GUID 後才可以使用 as 轉換}
i.Proc;
ShowMessage('**********');
{將依次顯示:
TMyClass.Create
IMyInterface.Proc
**********
TMyClass.Destroy
}
end;
procedure TForm1.Button4Click(Sender: TObject);
var
i: IMyInterface;
begin
i := TMyClass.Create;
i.Proc;
i := nil; //可以這樣主動釋放接口; 同時擁有它的類也會釋放
ShowMessage('**********');
{將依次顯示:
TMyClass.Create
IMyInterface.Proc
TMyClass.Destroy
**********
}
end;
end.