Search code examples
delphigenericsdelphi-2009factory

Generic factory


suppose I have a TModel:

TModelClass = class of TModel;
TModel = class
  procedure DoSomeStuff;
end;

and 2 descendants:

TModel_A = class(TModel);
TModel_B = class(TModel);

and a factory :

TModelFactory = class
  class function CreateModel_A: TModel_A;
  class function CreateModel_B: TModel_B;
end;

Now I want to refactor a bit :

TModelFactory = class
  class function CreateGenericModel(Model: TModelClass) : TModel
end;

class function TModelFactory.CreateGenericModel(Model: TModelClass) : TModel
begin
  ...
  case Model of
    TModel_A: Result := TModel_A.Create;
    TModel_B: Result := TModel_B.Create;
  end;
  ...
end;

So far it's ok, but every time I create a TModel descendant, I have to modify the factory case statement.

My question: Is this possible to create a 100% generic factory for all my TModel descendants, so every time I create a TModel descendants I don't have to modify TModelFactory ?

I tried to play with Delphi 2009 generics but didn't find valuable information, all are related to basic usage of TList<T>and so on.

Update Sorry, but maybe I'm not clear or don't understand your answer (I'm still a noob), but what i'm trying to achieve is :

var
  M: TModel_A;
begin
  M: TModelFactory.CreateGenericModel(MY_CONCRETE_CLASS);

Solution

  • If I understand your question properly, I wrote something similar here http://www.malcolmgroves.com/blog/?p=331