第一个例子的操作实况录像: 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、接口在用完后会自释放, 并同时释放拥有它的类; 这很方便, 但同时带来很多问题.
}