Einzelnen Beitrag anzeigen

Blup

Registriert seit: 7. Aug 2008
Ort: Brandenburg
1.464 Beiträge
 
Delphi 12 Athens
 
#12

AW: Klasse nach Vergleich mit Feld in Klasse erzeugen

  Alt 26. Mär 2012, 17:57
Im Prinzip muss die Factory die zu erzeugenden Klassen nicht einmal konkret kennen.
So kann man später beliebige Unterklassen ableiten, ohne TParentClass zu ändern:
Delphi-Quellcode:
unit UnitParentClass;

interface

uses
  Classes, Contnrs, SysUtils;

type
  TChildClassParams = record
    {...}
  end;

  TParentClass = class;
  TChildClassType = class of TParentClass;

  TParentClass = class
  private
    class var
      FClassList: TClassList;
    class procedure FreeList;
  protected
    class procedure Register(AClassType: TChildClassType);
    class function New(AParams: TChildClassParams; var AInstance: TParentClass): Boolean; virtual; abstract;
  public
    class function CreateInstance(AParams: TChildClassParams): TParentClass;
  end;

implementation

{ TParentClass }

class function TParentClass.CreateInstance(AParams: TChildClassParams): TParentClass;
var
  p: Pointer;
begin
  Result := nil;
  if Assigned(FClassList) then
  begin
    for p in FClassList do
    begin
      if TChildClassType(p).New(AParams, Result) then
        Exit;
    end;
  end;
end;

class procedure TParentClass.FreeList;
begin
  FreeAndNil(FClassList);
end;

class procedure TParentClass.Register(AClassType: TChildClassType);
begin
  if not Assigned(FClassList) then
    FClassList := TClassList.Create;

  FClassList.Add(AClassType);
end;

initialization

finalization
  TParentClass.FreeList;

end.
Delphi-Quellcode:
unit UnitChildClass;

interface

uses
  UnitParentClass;

type
  TChildClass = class(TParentClass)
  protected
    class function New(AParams: TChildClassParams; var AInstance: TParentClass): Boolean; override;
  end;

implementation

{ TChildClass }

class function TChildClass.New(AParams: TChildClassParams;
  var AInstance: TParentClass): Boolean;
begin
  Result := {AParams = ???} True;
  if Result then
    AInstance := Self.Create;
end;

initialization
  TChildClass.Register(TChildClass);

end.
  Mit Zitat antworten Zitat