第一個例子的操作實況錄像: http://flashview.ddvip.com/2009_06/Interface_Test.rar
代碼文件:
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;
IMyInterface1 = interface
function Func1: Integer;
function Func2: Integer;
end;
IMyInterface2 = interface
procedure Proc1;
procedure Proc2;
end;
TMyClass1 = class(TInterfacedObject, IMyInterface1, IMyInterface2)
public
procedure Proc1;
procedure Proc2;
function Func1: Integer;
function Func2: Integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TMyClass1 }
function TMyClass1.Func1: Integer;
begin
ShowMessage('IMyInterface1.Func1');
Result := 0;
end;
function TMyClass1.Func2: Integer;
begin
ShowMessage('IMyInterface1.Func2');
Result := 0;
end;
procedure TMyClass1.Proc1;
begin
ShowMessage('IMyInterface2.Proc1');
end;
procedure TMyClass1.Proc2;
begin
ShowMessage('IMyInterface2.Proc2');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
c: TMyClass1;
begin
c := TMyClass1.Create;
c.Func1;
c.Func2;
c.Proc1;
c.Proc2;
c.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
i1: IMyInterface1;
begin
i1 := TMyClass1.Create;
i1.Func1;
i1.Func2;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
i2: IMyInterface2;
begin
i2 := TMyClass1.Create;
i2.Proc1;
i2.Proc2;
end;
procedure TForm1.Button4Click(Sender: TObject);
var
c: TMyClass1;
i1: IMyInterface1;
i2: IMyInterface2;
begin
c := TMyClass1.Create;
i1 := c;
i1.Func1;
i1.Func2;
i2 := c;
i2.Proc1;
i2.Proc2;
// c.Free; {}
end;
end.
示例注釋(現在應該知道的):
{
1、接口命名約定 I 起頭, 就像類從 T 打頭一樣.
2、接口都是從 IInterface 繼承而來; 若是從根接口繼承, 可省略.
3、接口成員只能是方法、屬性, 沒有字段.
4、接口成員都是公開的, 不需要 private、protected、public、published 等任何訪問限制.
5、因為接口只聲明、無實現, 也用不到繼承與覆蓋相關的修飾(virtual、dynamic、abstract、override).
6、一個接口可以從另一個接口繼承, 但不能從多個接口繼承; 不過 Delphi.Net 已支持接口的多繼承了.
7、一個類可以實現多個接口: TMyClass = class(父類, 接口1, 接口2, ...) end;
8、不過實現接口的類有多麼豐富, 接口只擁有自己聲明的成員.
9、實現接口的類一般繼承於 TInterfacedObject, 直接從 TObject 繼承會增加一些麻煩而重復的工作.
10、接口在用完後會自釋放, 並同時釋放擁有它的類; 這很方便, 但同時帶來很多問題.
}