unit FormManager;
interface
uses
System.SysUtils, System.Classes,
System.Generics.Collections,
Vcl.Forms;
type
TFormManager =
class(TObject)
private
class constructor Create;
class destructor Destroy;
private
FContainer: TObjectDictionary<TFormClass, TForm>;
public
constructor Create;
destructor Destroy;
override;
function GetForm<T:
class,
constructor>: T;
procedure RegisterForm(
const AFormClass: TFormClass);
end;
function GetFormManager: TFormManager;
implementation
var
_FormManager: TFormManager;
function GetFormManager: TFormManager;
begin
Result := _FormManager;
end;
constructor TFormManager.Create;
begin
inherited;
FContainer := TObjectDictionary<TFormClass, TForm>.Create([doOwnsValues]);
end;
class constructor TFormManager.Create;
begin
_FormManager := TFormManager.Create;
end;
class destructor TFormManager.Destroy;
begin
_FormManager.Free;
end;
destructor TFormManager.Destroy;
begin
FContainer.Free;
inherited;
end;
function TFormManager.GetForm<T>: T;
var
LForm: TForm;
begin
if FContainer.TryGetValue(TFormClass(T), LForm)
then
begin
if not Assigned(LForm)
then
begin
LForm := TFormClass(T).Create(
nil);
FContainer.AddOrSetValue(TFormClass(T), LForm);
end;
Result := T(LForm);
end else
begin
Result :=
nil;
end;
end;
procedure TFormManager.RegisterForm(
const AFormClass: TFormClass);
begin
FContainer.Add(AFormClass,
nil);
end;
end.