Can a generic Delphi class go down from a class argument?

I am trying to define a generic, inherited TSingleton class. That's what I meant:

TSingleton<RealClass, InheritsFrom : class> = class(InheritsFrom) strict private class var FInstance : RealClass; protected procedure InstanceInitialization;virtual; public destructor Destroy; override; class procedure Create; reintroduce; class function Instance : RealClass; class procedure InstanceFree; end; 

The goal was to be able to "insert" a singleton pattern into the inheritance tree. so instead of declaring something like this:

  TMySingletonComponent = class(TComponent) end; 

And you need to implement a singleton pattern, I would declare something like this:

  TMyGenericSingletonComponent = class(TSingleton<TMyGenericSingletonComponent,TComponent>) end; 

Unfortunately this will not work. I get the following error (in D2010):

  TSingleton<RealClass, InheritsFrom : class> = class(InheritsFrom) ///E2021 Class type required 

Now I was wondering if this would work in Delphi XE? Is there any β€œclean hack” that I could use to make this work in D2010? Are there any fundamental reasons why this may not work?

+4
source share
3 answers

By design, you cannot create a generic class that derives from one of its type arguments.

+5
source

No, that will not work. You are trying to define a class in terms of yourself. Everything that you enter in the parameters must be fully defined.

+3
source

What do you want to get?

IMHO, singleton are evil. They were introduced due to the poor design of C ++ OOP (for access to input / output streams in console applications, as far as I remember). And they tend to support hell.

You can always live without them. This is ultimately not a classic way of Delphi programming, because Delphi does not suffer from the C ++ issues I mentioned.

Some Java projects (ab) use singleton. Google and you will find out what I mean.

Use a common class property with a getter, initializing the instance if the corresponding field is still zero or directly returns the field pointer to the instance if it is already created. You will have a singleton function with good performance, good code, good OOP practice (there is no "global" class) and the ability to run the class without any singleton function if you no longer need this function (for testing, for example).

+2
source

All Articles