Thursday, March 06, 2008

Design Patterns: Singleton

Again. Ensure a class only has one instance, and provide a global point of access to it.

class Singleton {
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};

Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance () {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}



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. [GOF]

1 comment:

  1. http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx

    ReplyDelete