Wednesday, March 23, 2011

Singleton Pattern

Motivation

Sometimes it's important to have only one instance for a class. For instance, there should be only one window manager (or only a file system or only a print spooler) in a system. Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
The singleton patterns is one of the simplest desing patterns and involves only one class which is responsible to instantiate itself only one instance and in the same time to provide a global point of access to the instance. In that case the instance can be used from everywhere without calling the directly the constructor each time.

Intent

•Ensure that only one instance of a class is created.
•Provide a global point of access to the object.

Implementation

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.

Applicability & Examples

According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point.

Here are some real situations where the singleton is used:


Example 1 - Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are ussualy implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 - Configuration Classes

The Singleton pattern is used to design the classes that provide the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoid reloading the values each time the configuration parameters are used.

Example 3 - Accesing resources in shared mode

It can be used in the design of an application that needs to work with the serial port. Let's say that there are many classs in the application, working in an multithreading environment, that needs to operate actions on the serial port. In this case a singleton with synchronized methods has to be used to manage all the operations on the serial port.

No comments:

Post a Comment