InterviewSolution
| 1. |
What is Singleton Design pattern? Explain with an example how to use Singleton Design pattern to design a class that is Thread safe |
|
Answer» Design Patterns are reusable SOLUTIONS that can be applied to recurring Object Oriented Design problems. Singleton is one such design PATTERN that comes under the category of Creational Design Pattern. It can be used to design such a class which can at most have only single instance at any point of time and cant be instantiated further. This concept can applied for creation of a logger or hardware interface class which can have only one instance running at all times. Example of Singleton class that is thread safe: In order to make the class thread safe, one needs to only create an instance when no other instance exists as below: class Singleton { public: static Singleton* getinstance(); ... private: static Singleton* VOLATILE newinstance; }; Singleton* Singleton::getinstance() { if (newinstance == NULL) { Guarder<LOCK>lock(m_lock); if (newinstance == NULL) { Singleton* volatile temp = static_cast< Singleton* >(operator NEW (sizeof(Singleton))); Newinstance = temp; } } return newinstance; } |
|