Einzelnen Beitrag anzeigen

Thomas_K

Registriert seit: 16. Apr 2006
71 Beiträge
 
Delphi XE8 Professional
 
#1

Lazy Initialization im Type?

  Alt 19. Feb 2015, 10:45
Ich bin in Codefragmente mehrfach auf folgendes Pattern gestoßen:
Code:
unit UnitUnknownLazyInitializationPattern;

interface

uses
  UnknownInterfaces, MoreUnknownUnits;

type
  TFoo = class
  private
    FMyUnknownObject: UnknownObject; // Type without the letter "T"?
    function GetMyUnknownObject: IUnknownObject;
  public
    property MyUnknowObject: IUnknownnObject read GetMyUnknownObject;
  end;

implementation

{ TFoo }

function TFoo.GetMyUnknownObject: IUnknownObject;
begin
  Result := FMyUnknownObject;
end;

end.
Und genutzt wird es so.
Code:
var
  Foo: TFoo;
begin
  Foo := TFoo.create;
  try
    Foo.MyUnknownObject.UnknownProcedure; // crash here, because UnknowProject still is nil
  finally
    Foo.free;
  end;
end;
Der Type von UnknowObject instanziiert Objekte bei Methoden Zugriffe selbst und kümmert sich auch um deren Freigabe(InterfacedObject, Smartpointer, ?).

Wie müsste die Implementierung von Type „UnknownObject“ aussehen, um diesen Effekt zu bekommen?
  Mit Zitat antworten Zitat