Einzelnen Beitrag anzeigen

Benutzerbild von Uwe Raabe
Uwe Raabe

Registriert seit: 20. Jan 2006
Ort: Lübbecke
11.015 Beiträge
 
Delphi 12 Athens
 
#21

AW: Designfrage: Liste selber schreiben? Oder von TList oder TList<T> ableiten?

  Alt 8. Sep 2014, 18:50
Dürfte ich dich eventuell aber noch einmal um ein Beispiel für diese Delegation der Implementation von Interfaces bitten? Ich find irgendwie nix, dass ich so wirklich verstehe.
Ist zwar auch etwas gekünstelt, aber probieren wir es mal hiermit (Günther's Beispiel ist zugegeben etwas lustiger):

Delphi-Quellcode:
type
  TDumpToJSON = class
  private
    FInstance: TObject;
  protected
    function DumpToJSON: string;
    property Instance: TObject read FInstance;
  public
    constructor Create(AInstance: TObject);
  end;

  IDumpToJSON = interface
    function DumpToJSON: string;
  end;

  TMyClass = class(TInterfacedPersistent, IDumpToJSON)
  private
    FDumpToJSON: TDumpToJSON;
    function GetDumpToJSON: TDumpToJSON;
  protected
    property DumpToJSON: TDumpToJSON read GetDumpToJSON implements IDumpToJSON;
  public
    destructor Destroy; override;
  end;

  TMyOtherClass = class(TInterfacedPersistent, IDumpToJSON)
  private
    FDumpToJSON: TDumpToJSON;
    function GetDumpToJSON: TDumpToJSON;
  protected
    property DumpToJSON: TDumpToJSON read GetDumpToJSON implements IDumpToJSON;
  public
    destructor Destroy; override;
  end;

constructor TDumpToJSON.Create(AInstance: TObject);
begin
  inherited Create;
  FInstance := AInstance;
end;

function TDumpToJSON.DumpToJSON: string;
begin
  result := TJson.ObjectToJsonString(Instance);
end;

destructor TMyClass.Destroy;
begin
  FDumpToJSON.Free;
  inherited Destroy;
end;

function TMyClass.GetDumpToJSON: TDumpToJSON;
begin
  if FDumpToJSON = nil then begin
    FDumpToJSON := TDumpToJSON.Create(Self);
  end;
  result := FDumpToJSON;
end;

destructor TMyOtherClass.Destroy;
begin
  FDumpToJSON.Free;
  inherited Destroy;
end;

function TMyOtherClass.GetDumpToJSON: TDumpToJSON;
begin
  if FDumpToJSON = nil then begin
    FDumpToJSON := TDumpToJSON.Create(Self);
  end;
  result := FDumpToJSON;
end;

Sowohl TMyClass als auch TMyOtherClass leiten die Implementierung des Interfaces an die Instanz einer anderen Klasse TDumpToJSON weiter, die interessanterweise über IDumpToJSON gar nichts weiß.
Uwe Raabe
Certified Delphi Master Developer
Embarcadero MVP
Blog: The Art of Delphi Programming
  Mit Zitat antworten Zitat