Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - inherit from a class and an interface (adapter pattern)?

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.

Am I correct?

Thank you.

I have implemented this pattern on http://delphipatterns.blog.com/2011/02/22/decorator-5/

like image 515
elector Avatar asked Dec 09 '22 10:12

elector


1 Answers

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;
like image 168
David Heffernan Avatar answered Feb 16 '23 01:02

David Heffernan