Creating a real singleton class in delphi
The article describes how to create a class that follows the singleton pattern. The class described will take care of the singleton requirements and effects itself, effectively leaving the programmer to use the class as any others.
A singleton is a class that supports the creation of just one object. It's like your computer -- there's just one keyboard. So if you were writing Delphi code that simulated your computer, you would want just one object instance to deal with keyboard read, write, and control activities.
Articles about singleton classes are rare but there are a few on the Internet. I've seen some in magazines too. But none of these articles include sample code to create a real singleton class.
By "real" I mean that the class itself enforces the one-instance requirement, instead of leaving that task to the programmer. All of the articles I have seen so far have required the programmer to use the class in a special way to enforce the singleton pattern.
In this article you will see how to create a proper singleton class that includes logic to enforce the one-instance rule.
Note: The conventional approach, in which the one-instance rule is maintained explicitly by the programmer, is not without merit. Real singleton classes like the one I present here effectively hide the details and awareness of the singleton pattern from the programmer. The programmer is relieved of the task of enforcing the pattern -- that's good -- but the programmer may also be unaware of the special nature of the class, which is bad. If you don't know that the class is a singleton class then all sorts of errors can crop up. You have been warned!
Writing the code
Our goal is to write a class that can be used like this:
procedure Test;
var
s1, s2 : TSingleton;
begin
s1 := TSingleton.Create;
s2 := TSingleton.Create;
// Do something with s1 and s2 here
s2.Free;
s1.Free;
end;
(I've left out the try...finally blocks and other safeguards for simplicity's sake.)
The goal is to make the TSingleton class behave in such a way that both s1 and s2 refer to the same object. Here's what we have to do:
Instantiate the object the first time Create is called (when s1 is created above)
Ensure that when another Create is executed (s2 above), the existing object is reused instead of another one created
Avoid destroying the object when it's not the last reference that is destroyed (when s2 is freed)
Destroy the instance when the last reference is destroyed (when s1 is freed above)
Is there a way to override the creation and destruction of a new object in Delphi? There sure is. In the TObject class (the mother of all objects {pun intended}), there are two methods we can use:
class function NewInstance: TObject; virtual;
procedure FreeInstance; virtual;
NewInstance is responsible for allocating memory to hold a new instance of the class, and FreeInstance is responsible for freeing that memory when the class is through with it.
These methods control what happens when the object is created and when the object is destroyed. If we overwrite this code, we can alter the default behavior to work the say a singleton class requires. Nothing to it.
Tracking instances is a little trickier. We must:
Keep track of each existing instance of our class
Keep track of how many references there are to this instance
Create a new object only when no instance exists
Destroy the object when the last reference is removed
To keep track of an existing instance, we will use a global variable. Actually, the variable will ultimately be declared inside the Implementation part of a unit so it won't be a true global variable. But the scope must be sufficient to track all the Create and Free calls. We'll call the variable Instance so we know what it refers to.
As for keeping track of how many references exist, we need another variable. We can it inside the class or make it a sort-of global like Instance. I'll opt for the latter way but do what you feel is best. I'll name this variable Ref_Count.
We now have two variables:
var
Instance : TSingleton = nil;
Ref_Count : Integer = 0;
I initialize the variables so that initially they don't contain any garbage. I know that the compiler does this automatically, so this is just a readability issue.
We'll need to declare the TSingleton class above the variable block, and if you take a look at the example files that you can download at the end of this article you'll see that I've put the declaration in the interface part of the unit so that it's visible outside of it.
Here's the declaration of the TSingleton class:
type
TSingleton = class
public
class function NewInstance: TObject; override;
procedure FreeInstance; override;
class function..