Ensure a class only has one instance, and provide a global point of access to it.
It's important for some classes to have exactly one instance. Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager. A digital filter will have one A/D converter. An accounting system will be dedicated to serving one company.
How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects.
A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. This is the Singleton pattern.
As an example we will apply the
singleton pattern to a single database connection:
The global variable SingleConnection
points to an invalid DatabaseConnection
or to the first valid DatabaseConnection.
Two successive calls to the
DatabaseConnection constructor returns in both cases the first
This page was last modified on 01-10-2012 14:54:39