TransWikia.com

Implementing an interface with partial delegation

Stack Overflow Asked by Fabrizio on November 22, 2021

I have a subobject who implements only a part of an interface:

  IMyTest = interface
    procedure P1;
    procedure P2;
  end;

  TMyTestP2Impl = class
    procedure P2;
  end;

  TMyTest = class(TInterfacedPersistent, IMyTest)
  private
    FMyTestP2Impl : TMyTestP2Impl;
  public
    constructor Create();
    destructor  Destroy(); override;
    procedure P1;
    procedure P2;
  end;

So I have to write TMyTest.P2 as follows:

procedure TMyTest.P2;
begin
  FMyTestP2Impl.P2();
end;

I’m wondering if there is a valid syntax for mapping TMyTest.P2 to FMyTestP2Impl.P2 without writing the implementation for TMyTest.P2. I mean something like the following:

  TMyTest = class(TInterfacedPersistent, IMyTest)
  private
    FMyTestP2Impl : TMyTestP2Impl;
  public
    constructor Create();
    destructor  Destroy(); override;
    procedure P1;
    procedure P2 = FMyTestP2Impl.P2;
  end;

One Answer

You have to use delegation to a class type property:

type
  IMyTest = interface
    procedure P1;
    procedure P2;
  end;

  TMyTestP2Impl = class
    procedure P2;
  end;

  TMyTest = class(TInterfacedPersistent, IMyTest)
  private
    FMyTestP2Impl: TMyTestP2Impl;
    property MyTestP2Impl: TMyTestP2Impl read FMyTestP2Impl implements IMyTest;
  public
    constructor Create;
    destructor  Destroy; override;
    procedure P1;
  end;

Answered by Stefan Glienke on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP