【发布时间】:2015-01-15 10:43:40
【问题描述】:
我必须编写一些接口来实现一些类。其中一些将具有“基本”行为,其他将具有一些“高级”功能。
我认为最好的方法是声明一个“基本”interface 和一个“高级”子 interface。
我也试图保持对象和接口之间的松散耦合。
现在我遇到了这个问题:
当我创建一个“高级”对象(实现子接口)时,我希望它也实现父接口,但“getInterface”和“支持”似乎都不同意我的观点。
这是一个示例代码:
type
IParent = interface
['{684895A1-66A5-4E9F-A509-FCF739F3F227}']
function ParentFunction: String;
end;
IChild = interface(IParent)
['{B785591A-E816-4D90-BA01-1FFF865D312A}']
function ChildFunction: String;
end;
TMyClass = class(TInterfacedObject, IChild)
public
function ParentFunction: String;
function ChildFunction: String;
end;
function TMyClass.ChildFunction: String;
begin
Result := 'ChildFunction';
end;
function TMyClass.ParentFunction: String;
begin
Result := 'ParentFunction';
end;
var
Obj: TMyClass;
ParentObj: IParent;
ChildObj: IChild;
begin
Obj := TMyClass.Create;
ChildObj := Obj;
WriteLn(Format('%s as IChild: %s', [Obj.ClassName, ChildObj.ChildFunction]));
WriteLn(Format('%s as IChild: %s', [Obj.ClassName, ChildObj.ParentFunction]));
if (Obj.GetInterface(IParent, ParentObj)) then
WriteLn(Format('GetInterface: %s as IParent: %s', [Obj.ClassName, ParentObj.ParentFunction]))
else
WriteLn(Format('GetInterface: %s DOES NOT implement IParent', [Obj.ClassName])); // <-- Why?
ParentObj := ChildObj;
WriteLn(Format('%s as IParent: %s', [Obj.ClassName, ParentObj.ParentFunction]));
if (Supports(Obj, IParent)) then
WriteLn(Format('Supports: %s Supports IParent', [Obj.ClassName]))
else
WriteLn(Format('Supports: %s DOES NOT Support IParent', [Obj.ClassName])); // <-- Why?
end.
结果如下:
TMyClass as IChild: ChildFunction
TMyClass as IChild: ParentFunction
GetInterface: TMyClass DOES NOT implement IParent
TMyClass as IParent: ParentFunction
Supports: TMyClass DOES NOT Support IParent
例如,我如何测试一个对象是否实现了IParent 或它的后代?
谢谢
【问题讨论】:
-
如果你想支持接口,你必须实现接口,因为每个实现类可以以不同的方式实现接口。看看pastebin.com/PkQidhFc
标签: delphi inheritance interface delphi-7