I’m a big fan of singleton patterns, basically a singleton pattern lets a class maintain a single instance of itself which you can then reuse as often as you want without having to create a new instance. This is achieved by creating a private static field inside the class that can hold an instance of itself, when the user wants to retrieve the instance for the first time, a new one is created and stored in the field, if there’s already one present, the class will return that instance. The implementation I usually use also has automated cleaning of the instance once the application terminates by adding a shared constructor. It’s also possible to add a private constructor to the class to disable the coder to create any instances of it directly without using the singleton pattern or subclassing it.
Here’s an example of the singleton pattern with cleaning:
type TTestClass = class private class var FInstance: TTestClass; public class function GetInstance: TTestClass; class destructor DestroyClass; end; { TTestClass } class destructor TTestClass.DestroyClass; begin if Assigned(FInstance) then FInstance.Free; end; class function TTestClass.GetInstance: TTestClass; begin if not Assigned(FInstance) then FInstance := TTestClass.Create; Result := FInstance; end;
It’s also possible to add a property named Instance or something even shorter that will get the instance from the GetInstance method which you would then make private, this will shorten the amount of code you have to write when using it.
Hello
what version of Delphi are you using?
Thank you
Delphi 2010, I have but do not feel the need to upgrade to XE. This code will probably not compile on versions older than 2010, maybe 2009, because class destructors haven’t been around for that long.
Nice to see they’ve added class variables, now (or perhaps in D 2009?)
I don’t know when exactly, but at least in D2009, maybe before. Though as I recall, class methods have been in there a lot longer.