How can i make a generic class factory ?
Cant make this generic class factory work.
{
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
}
// Copyright (c) 2010 2011 2012 2013 2014 2015 - J. Aldo G. de Freitas Junior
{$mode objfpc}
{$H+}{$M+}
Unit
GenericClassFactory;
Interface
Uses
{$ifdef unix}
cthreads,
cmem,
{$endif}
SysUtils,
Contnrs,
RTTIObjects;
Type
EGenericClassFactory = Class(Exception);
Generic GGenericClassFactory<ObjectType> = Class
Type
TGenericType = ObjectType;
TGenericTypeClass = Class Of TGenericType;
Private
fMutex : TMultiReadExclusiveWriteSynchronizer;
fHashTable : TFPHashList;
Public
Constructor Create;
Destructor Destroy; Override;
Procedure Register(Const aClass : TClass; Const aName : String = '');
Function Build(Const aName : String): TGenericType;
End;
Implementation
Constructor GGenericClassFactory.Create;
Begin
Inherited;
fMutex := TMultiReadExclusiveWriteSynchronizer.Create;
fHashTable := TFPHashList.Create;
End;
Destructor GGenericClassFactory.Destroy;
Begin
FreeAndNil(fMutex);
FreeAndNil(fHashTable);
Inherited;
End;
Procedure GGenericClassFactory.Register(Const aClass : TClass; Const aName : String = '');
Begin
Try
fMutex.BeginWrite;
If aName = '' Then
fHashTable.Add(aClass.ClassName, Pointer(aClass))
Else
fHashTable.Add(aName, aClass);
Finally
fMutex.EndWrite;
End;
End;
Function GGenericClassFactory.Build(Const aName : String): TGenericType;
Var
lIndex : Integer;
Begin
Try
fMutex.BeginRead;
lIndex := fHashTable.FindIndexOf(aName);
If lIndex >= 0 Then
Begin
Build := TGenericTypeClass(fHashTable.Items[lIndex]).Create;
End
Else
Raise EGenericClassFactory.Create('Type ' + aName + ' is not registered in this class factory.');
Finally
fMutex.EndRead;
End;
End;
End.