作者:隔壁老吴 | 来源:互联网 | 2023-05-24 11:48
我正在阅读Nick Hodges的书"Delphi中的编码",我正在尝试理解界面的用法.在一个单元中我放置了简单的界面:
unit INameInterface;
interface
type
IName = interface
['{CE5E1B61-6F44-472B-AE9E-54FF1CAE0D70}']
function FirstName: string;
function LastName: string;
end;
implementation
end.
在另一个单元中我已经把这个接口的实现,根据书样本:
unit INameImplementation;
interface
uses
INameInterface;
type
TPerson = class(TInterfacedObject, IName)
protected
function FirstName: string;
function LastName: string;
end;
implementation
{ TPerson }
function TPerson.FirstName: string;
begin
Result := 'Fred';
end;
function TPerson.LastName: string;
begin
Result := 'Flinstone';
end;
end.
此时我已经创建了一个简单的VCL表单应用程序,以便使用我创建的对象.表单代码是这样的:
unit main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, INameImplementation;
type
TfrmMain = class(TForm)
lblFirtName: TLabel;
lblLastName: TLabel;
txtFirstName: TStaticText;
txtLastName: TStaticText;
btnGetName: TButton;
procedure btnGetNameClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
Person: TPerson;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
txtFirstName.Caption := '';
txtLastName.Caption := '';
end;
procedure TfrmMain.btnGetNameClick(Sender: TObject);
begin
txtFirstName.Caption := ...
end;
end.
我的问题是:我该如何使用界面?这两个函数被声明为protected,所以如何从表单中访问它们?我要将它们定义为public,还是应该使用INameInterface接口单元?我对界面非常困惑!
性爱
1> David Heffer..:
基本上有三件事你可以知道,除了你已经证明的理解.
1.如何调用接口的方法
如果您有对接口的引用,那么您可以像在类引用上一样调用方法:
var
Name: IName;
....
Writeln(Name.FirstName);
Writeln(Name.LastName);
2.如何获取接口引用
通常,您可以通过实例化实现您希望使用的接口的类来执行此操作:
var
Name: IName;
....
Name := TPerson.Create;
// now you can use Name as before
还有其他方法可以获得接口引用,但是让我们暂时将它们留在一边.
3.如何传递接口
您可能不希望每次需要使用接口时都创建新对象.因此,您可以让其他方通过您使用的界面.例如,接口可以作为方法参数传递:
procedure Foo(Name: IName);
begin
// use Name as before
end;
您可以通过函数调用和属性等获取接口引用.
这两个函数被声明为protected
如何从表单中访问它们?
好吧,它们protected
在实现对象中声明.但是你不会通过实现对象访问它们.您将通过界面访问它们.这意味着从接口的角度来看,实现对象中的可见性是不相关的.
表单单元引用INameImplementation
创建实现接口的对象所需的引用.您还需要使用,INameInterface
以便您的代码可以看到界面本身.
这个例子还不是很强大,因为你仍然可以看到实现对象的类型.但想象一下,如果这对你隐藏,你所能看到的只是一个返回的函数IName
.当你达到这一点时,接口可以发挥其潜力.