Singleton Pattern Applicability & Examples
by, 03-09-2012 at 06:43 PM (727 Views)
Singleton Pattern according to its definition shall be only used if there is exact one instance of class and also when its accessibility is given from a global access point to the clients.Few real situations are given here where singleton is used:
In design of the logger class the singleton pattern is used. Such classes are basically implemented as singletons so that to provide a global access point for all the components of application. For this purpose it is not essential to build an object everytime a logging operation takes place.
To design the class, singleton pattern is used. This helps to provide the configuration setting of some application. Implementation of the configuration classes as a singleton provides global access point and also keeps the instance that is used as a cache object by us. Values would be kept in internal structure by singleton, when class gets instantiated. When values are read from files or from the database than it would avoid the value’s reloading every time the parameters of configuration are used.
Resources access in shared mode
For design of application which requires to work along with serial port, it could be used. For example, numbers of classes are present in application which work in multi threading environment and require operating the actions at serial port. In such cases, singleton along with some synchronized method is used for managing the serial port’s overall operations.
Factories that have been implemented as Singletons
Assume that in a multi threading environment, we are designing some application with a factory so that to create new objects along with their ids. If twice instantiation of the factory takes place in two different threads it means that possibility exists for two different objects to have two overlapping ids. If factory gets implemented as a singleton than avoid this problem. It is considered a common practice to combine the factory method or abstract factory and singleton designing patterns.