接口定义就像一份合同,它规定了客户如何按照特写的顺序使用特定的方法。
例如:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
IJuCanSwim = interface(IUnknown)
['{199F1484-8738-4666-9862-020E593E83A2}']
function Swim(): string;
end;
TJuFish = class(TInterfacedObject, IJuCanSwim)
public
function Swim(): string
virtual;
end;
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TJuFish }
function TJuFish.Swim: string;
begin
Result := 'Yes. I can swim.';
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Fish: TJuFish;
begin
Fish := TJuFish.Create();
try
Memo1.Lines.Add('TJuFish::');
Memo1.Lines.Add(Fish.Swim());
finally
Fish.Free();
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
CanSwim: IJuCanSwim;
begin
CanSwim := TJuFish.Create() as IJuCanSwim;
Memo1.Lines.Add('IJuCanSwim::');
Memo1.Lines.Add(CanSwim.Swim());
end;
end.