///
// Singleton Pattern
// - Ensure a class only has one instance, and provide a global point
// of access to it.
//
// Author : ZAsia
// Data : 15/05/07
// Warning : In practice, declaration and implementation should be
// separated(in .h and .cpp).
///
#include
using namespace std;
// Singleton
// - defines an Instance operation that lets clients access its unique
// instance. Instance is a class operation(that is, a static member
// member function in C++).
// - may be responsible for creating its own unique instance.
class Singleton
{
public:
static Singleton *Instance()
{
if (_instance == nullptr)
{
_instance = new Singleton();
}
return _instance;
}
protected:
Singleton() { cout << "Singleton..." << endl; }
private:
static Singleton *_instance;
};
Singleton *Singleton::_instance = nullptr;
// Collaborations
// - Clients access a Singleton instance solely through Singleton's
// Instance operation.
int main()
{
Singleton *singletonObj = Singleton::Instance();
if (singletonObj != nullptr)
{
delete singletonObj;
singletonObj = nullptr;
}
return 0;
}
// 1. Controlled access to sole instance. Because the Sinleton class
// encapsulates its sole instance, it can hvae strict control over
// how and when clients access it.
// Notice that the constructor is protected. A client that tries to
// instantiate Singleton directly will get an error at compile-time.
// This ensures that only one instance can ever get created.
// 2. Reduced name space. The Singleton pattern is an improvement over
// global variables. It avoids pollting the name space with global
// variables that store sole instances.
DesignPatterns_Singleton
最新推荐文章于 2018-04-25 21:46:23 发布