代码文件:

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.

posted on 2009-06-05 10:42  万一  阅读(12900)  评论(8编辑  收藏  举报