In our previous post, we discussed about singleton design pattern. Now, we will see where is its applicability.
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. If there is multiple client application using this logging utility class they might create multiple instances of this class and it can potentially cause issues during concurrent access to the same logger file.
Example 2 – Configuration Classes
The Singleton pattern is used to design the classes which provides 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 avoids the 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 classes in the application, working in an multi-threading environment. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port. Hardware printers where the print spooler can be made a singleton to avoid multiple concurrent accesses and creating deadlock.
Example 4 – Cache
We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object.