Einzelnen Beitrag anzeigen

TigerLilly

Registriert seit: 24. Mai 2017
Ort: Wien, Österreich
1.176 Beiträge
 
Delphi 11 Alexandria
 
#12

AW: Entkoppeln von Forms

  Alt 12. Sep 2017, 15:39
Ich hab jetzt mal sowas:

Delphi-Quellcode:
type
  TCreateFormFunction = reference to function(Owner: TComponent): TForm;

  TFormFactory = class
    FList: TDictionary<string, TCreateFormFunction>;
  public
    constructor Create; virtual;
    procedure RegisterForm(sName: String; CreateFormFunction: TCreateFormFunction);
    function CreateForm(sName: String; Owner: TComponent): TForm; virtual;
  end;

implementation

constructor TFormFactory.Create;
begin
  FList := TDictionary<string, TCreateFormFunction>.Create;
end;

function TFormFactory.CreateForm(sName: String; Owner: TComponent): TForm;
begin
  Result := FList[sName](Owner);
end;

procedure TFormFactory.RegisterForm(sName: String; CreateFormFunction: TCreateFormFunction);
begin
  FList.Add(sName, CreateFormFunction);
end;
Damit kann eine eigene Unit, die einzelnen Forms registrieren:
Delphi-Quellcode:
var
  FormFactory: TFormFactory;

implementation

uses
  Form01.View, Form02.View;

procedure Formregistration;
begin
  FormFactory := TFormFactory.Create;
  FormFactory.RegisterForm('Form02',
    function(Owner: TComponent): TForm
    begin
      Result := TForm02.Create(Owner);
    end);
  FormFactory.RegisterForm('Form01',
    function(Owner: TComponent): TForm
    begin
      Result := TForm01.Create(Owner);
    end);
end;
Und mein Form01, der gar nichts von Form02 weiß, kann dieses machen:
  Formfactory.CreateForm('Form02',Self).Show; Das ist doch schon mal nett.

Das verfeinere ich jetzt noch wie folgt:
- Interfaces statt TForms
- Ich will ja nicht x-beliebige Forms registrieren, Sinn hat das ja nur für jene, die das gleiche tun. Also eine eigene factory je Interface.

Mal sehen.

Feedback gerne, danke.
  Mit Zitat antworten Zitat