2015-04-30 26 views
1

我有一组派生自基类的类。 基类表示要调用的通用服务(实际上是一种REST客户端),每个派生类都是每个特定服务(具有特定参数)的包装。 请注意,我的基类实现Interface德尔福:从接口引用调用子类的方法

下面是一些简单的代码:

IMyService = interface 
    ['{049FBEBD-97A8-4F92-9CC3-51845B4924B7}'] 
    function GetResponseContent: String; 
    // (let's say AParams is a comma-delimited list of name=value pairs) 
    procedure DoRequest(const AParams: String); overload; // (1) 
    property ResponseContent: String read GetResponseContent; 
end; 

TMyBaseService = class(TInterfacedObject, IMyService) 
protected 
    FResponseContent: String; 
    function GetResponseContent: String; 
public 
    procedure DoRequest(const AParams: String); overload; // (1) 
    property ResponseContent: String; 
end; 

TFooService = class(TMyBaseService) 
public 
    // This specific version will build a list and call DoRequest version (1) 
    procedure DoRequest(AFooParam1: Integer; AFooParam2: Boolean); overload; // (2) 
end; 

TBarService = class(TMyBaseService) 
public 
    // This specific version will build a list and call DoRequest version (1) 
    procedure DoRequest(ABarParam1: String); overload; // (3) 
end; 

现在,我可以随时创建,并且在一般,后期定制绑定的方式调用服务,传递则params的“开放”列表中( 1)和穿越我的手指:

var 
    Foo, Bar: IMyService; 
begin 
    Foo := TFooService.Create; 
    Bar := TBarService.Create; 
    Foo.DoRequest('name1=value1,name2=value2'); 
end; 

但是,什么叫具体DoRequest标记为最好的方式(2)和(3)?

我不能施放接口引用对象TFooService(Foo).DoRequest(2, False)
和因为我需要使用用于ARC的界面的参考(自动引用计数)我不能声明Foo: TFooService

回答

1

使接口代表其他功能。例如:

type 
    IFooService = interface 
    [GUID here] 
    procedure DoRequest(AFooParam1: Integer; AFooParam2: Boolean); overload; 
    end; 

TFooService实现它

type 
    TFooService = class(TMyBaseService, IFooService) 
    .... 

然后使用as来获得这些数据:

var 
    Foo: IMyService; 
.... 
(Foo as IFooService).DoRequest(AFooParam1, AFooParam2); 
+0

谢谢大卫,现在它按预期工作! – yankee