By: Lasse V#gs?ther Karlsen
Abstract: 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.
by Lasse Vegsfther Karlsen, Systems Developer for
Cintra Software Engineering
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!
Our goal is to write a class that can be used like this:
s1, s2 : TSingleton;
s1 := TSingleton.Create;
s2 := TSingleton.Create;
// Do something with s1 and s2 here
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:
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:
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
We now have two variables:
Instance : TSingleton = nil;
Ref_Count : Integer = 0;
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:
TSingleton = class
class function NewInstance: TObject; override;
procedure FreeInstance; override;
class function RefCount: Integer;
Ok, now for the implementation of the three methods:
Dec( Ref_Count );
if ( Ref_Count = 0 ) then
Instance := nil;
// Destroy private variables here
class function TSingleton.NewInstance: TObject;
if ( not Assigned( Instance ) ) then
Instance := inherited NewInstance;
// Initialize private variables here, like this:
// TSingleton(Result).Variable := Value;
Result := Instance
Inc( Ref_Count );
class function TSingleton.RefCount: Integer;
Result := Ref_Count;
When you call TSingleton's constructor, a call is placed to the NewInstance method
declared in TObject. This method allocates memory to hold the new
object and returns it to the constructor. The constructor uses
that memory and eventually returns a pointer to the memory to the code
that called the constructor. This pointer is usually stored in a variable
while the object is in use.
I have overridden the NewInstance method so it will allocate the memory
only if no instance of the class exists. If there is an existing instance,
the function simply
returns that instance to the constructor so it will be reused.
If we call the constructor three times, an object is created only the first
time. The other two calls simply reuse the first object. The reference count
variable let us know that we have three references to the single instance.
When the program calls the destructor, a call to
FreeInstance is placed to free the memory allocated in the
constructor. This method, too, is overridden so that the object is destroyed
only when the last reference is removed.
If you intend to use a singleton in a multithreaded program, treat the
object as you would any variable you share between threads. Because
that's just what you do: share it between the threads. So you
must take special care when changing data.
As you can see, creating a singleton class doesn't require much effort, just
the right knowledge and a few lines of code. My code works fine in Delphi 5.
The technique will probably work fine with older versions of Delphi, but I
haven't tested it so I don't make any guarantees.
Before I give you the file to play with, let me give you a few words
Link to file: CodeCentral entry 15083.
I'm sure you can find a few places where a singleton class comes in handy
and now you have the tools to create your own! If you want to get in touch with me, my email is
Download Delphi XE5 and create Android apps!
Get Free Trial
Webinars on demand!
More social media choices:
Delphi on Google+
@RADTools on Twitter
Server Response from: ETNASC02