I’m looking to create a singleton in Delphi. I’ve done this before using older versions of Delphi, and ended up using global variables (in the implementation section) and using initialization and finalization to take care of the instance. Also there was no way of preventing the user from creating an instance as you couldn’t hide the standard constructor. I was wondering if any of the new features such as class constructors and destructors, and class variables (ok, not so new), perhaps generics, could help in creating a generic singleton class. I haven’t managed to create something to my satisfaction yet.
Share
It was possible to manage this by overriding the TRUE allocator and deallocator methods in Delphi, NewInstance and FreeInstance. Constructors and Destructors in Delphi only initialise and finalise respectively, they do not allocate or deallocate memory, so attempting to hide constructors was always a little misguided.
i.e. it was possible to allow free use of any and all constructors as long as you overrode NewInstance such that it only ever returned a reference to one single allocation of memory for the class.
But attempting to enforce a usage/behavioural pattern in a base class is a mistake imho. Not ALL patterns are or require specific classes to encapsulate the pattern.
In cases such as this you end up creating something that is needlessly complicated, and complication attracts errors in my experience and the object of the exercise then becomes trying to find flaws in the pattern implementation and then trying to implement safeguards against those flaws, rather than getting on with the practical job of work that the singleton class was supposed to perform.
It is far, FAR simpler and more effective to document the USAGE of the class.
Documentation as a technique for implementing this pattern has worked flawlessly for 15 years for the Application and Screen objects in the VCL, for example, not to mention countless other singletons that I’ve created in those years.