DIR Return Create A Forum - Home
---------------------------------------------------------
ifaq
HTML https://ifaq.createaforum.com
---------------------------------------------------------
*****************************************************
DIR Return to: C/C++ related questions
*****************************************************
#Post#: 12--------------------------------------------------
Simgleton pattern
By: avinash.srin Date: August 25, 2011, 9:48 am
---------------------------------------------------------
What is the Single design pattern? Implement it in C++.
#Post#: 15--------------------------------------------------
Re: Simgleton pattern
By: avinash.srin Date: August 26, 2011, 5:04 am
---------------------------------------------------------
It is the case where we need to use a single object of a class
throughout the lifetime of an application.
One of the ways to implement it in C++ is as follows:
[code]
class MySingleton {
public:
static MySingleton& Instance() {
static MySingleton singleton;
return singleton;
}
// Other non-static member functions
private:
MySingleton() {}; // Private
constructor
MySingleton(const MySingleton&); // Prevent
copy-construction
MySingleton& operator=(const MySingleton&); // Prevent
assignment
};
[/code]
#Post#: 27--------------------------------------------------
Re: Simgleton pattern
By: bloodkamal Date: September 6, 2011, 12:28 am
---------------------------------------------------------
Any realtime example where singleton is useful?
#Post#: 28--------------------------------------------------
Re: Simgleton pattern
By: avinash.srin Date: September 14, 2011, 6:28 am
---------------------------------------------------------
There is a requirement for a NetworkDeviceManager class whose
functionality is to maintain a list of NetworkDevices in a
Network Management System. There can be 'n' number of Network
Devices and only one NetworkDeviceManager at any point of time
in the application. Each time a NetworkDevice is added to the
system, the NetworkDeviceManager is invoked and the
NetworkDevice is added to it.
The same example when implemented, the NetworkDeviceManager
instance maintains a vector of NetworkDevice objects. Whenever,
a NetworkDevice object is instantiated and added to the system,
it has to invoke the same NetworkDeviceManager instance and add
itself to the vector maintained by the NetworkDeviceManager.
In this case, the NetworkDeviceManager can be implemented as a
Singleton class, which gives it a global presence as well as
ensures that no duplicate instance is created.
*****************************************************