Delphi - 从类和接口继承(适配器模式)? [英] Delphi - inherit from a class and an interface (adapter pattern)?

查看:177
本文介绍了Delphi - 从类和接口继承(适配器模式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行GoF适配器模式,并且在C#示例中,我遵循Adapter类继承原始类和适配接口。
在Delphi(2007)中,据我所知,这是不可能的,或者是这样吗?如果一个类继承一个接口,它需要继承TInterfacedObject,因为Delphi不允许多个类继承,这就是故事的结尾。我不能同时从自定义类和接口继承。

I am trying to do the GoF adapter pattern and in the C# example that I am following the Adapter class is inheriting the original class and an adapting interface. In Delphi (2007), as far as I know, this is not possible, or is it? Cause if a class is inheriting an interface, it needs to inherit from TInterfacedObject and since Delphi doesn't allow multiple class inheritance, that is the end of story. I cannot inherit from a custom class and an interface at the same time.

我是否正确?

谢谢你。

我在 http://delphipatterns.blog.com/2011/02/22/decorator-5/

推荐答案

不,这不正确。您可以将接口添加到您喜欢的任何类中,如下所示:

No that it not correct. You can add an interface to any class you like as follows:

type
  IAdapter = interface
    procedure DoSomething;
  end;

  TAdapter = class(TBaseClass, IInterface, IAdapter)
  private
    FRefCount: Integer;
    procedure DoSomething;
  protected
    function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
  end;

function TAdapter.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
  if GetInterface(IID, Obj) then
    Result := 0
  else
    Result := E_NOINTERFACE;
end;

function TAdapter._AddRef: Integer;
begin
  Result := InterlockedIncrement(FRefCount);
end;

function TAdapter._Release: Integer;
begin
  Result := InterlockedDecrement(FRefCount);
  if Result = 0 then
    Destroy;
end;

procedure TAdapter.DoSomething;
begin
end;

这篇关于Delphi - 从类和接口继承(适配器模式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆