Einzelnen Beitrag anzeigen

Benutzerbild von Mavarik
Mavarik

Registriert seit: 9. Feb 2006
Ort: Stolberg (Rhld)
4.130 Beiträge
 
Delphi 10.3 Rio
 
#9

AW: Beliebige Klasse instanzieren

  Alt 28. Okt 2015, 21:25
Die klassische Factory ist ja statisch in dem Sinne, dass mir zur Laufzeit alle Implementierungen bekannt sein müssen, damit ich nach Typ unterscheiden kann. Das brauch und wollte ich eigentlich nicht. Ich will offen sein.
Naja der Typ muss schon bekannt sein...
Jedenfalls zum Zeitpunkt wo Du eine Instance erzeugen willst...

Die Instance muss nicht bekannt sein in der Unit von der Du das Aufrufst...

Normalerweise nimmt man für sowas ein Dictionary und Registriert daran die Implementationen... Mit dem TypeInfo...

Aber ein Beispiel ohne alles...:

Delphi-Quellcode:
program Project97;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
   MyInterface = interface
     Function FooCalc(Const AValue : Integer) : Integer;
   end;

   TImpl1 = Class(TInterfacedObject,MyInterface)
     private
       Function FooCalc(Const AValue : Integer) : Integer;
   end;

   TImpl2 = Class(TInterfacedObject,MyInterface)
     private
       Function FooCalc(Const AValue : Integer) : Integer;
   end;

{ TImpl1 }

function TImpl1.FooCalc(const AValue: Integer): Integer;
begin
  Result := AValue * 2;
end;

{ TImpl2 }

function TImpl2.FooCalc(const AValue: Integer): Integer;
begin
  Result := AValue - 10;
end;

Function GetFoo(Const AName : String;Const AValue : Integer):Integer;
var
  IFooCalc : MyInterface;
begin
  if AName = 'Impl1// Normalerweise Implementation aus Dictionary holen...
    then IFooCalc := TImpl1.Create
    else IFooCalc := TImpl2.Create;

  Result := IFooCalc.FooCalc(AValue);
end;

begin
  try
    { TODO -oUser -cConsole Main : Code hier einfügen }
    Writeln('Interface "Factory"');
    Writeln('Die Frage aller Fragen ...');
    Writeln('FooCalc1 1 mit 21 = '+ Inttostr(GetFoo('Impl1',21))); // Implementation nicht bekannt...
    Writeln('FooCalc1 2 mit 52 = '+ Inttostr(GetFoo('Impl2',52)));
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
  Mit Zitat antworten Zitat