Saturday, May 9, 2009

Singleton Design Pattern in c++

if you want a class that has only one representation in the proccess


declaration

class Singleton
{
public: static Singleton* Instance();
protected: Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private:
static Singleton* pinstance;
};

implementation

Singleton* Singleton::pinstance = 0;// initialize pointer

Singleton* Singleton::Instance ()
{
if (pinstance == 0) // is it the first call?
{
pinstance = new Singleton; // create sole instance
}
return pinstance; // address of sole instance
}

Singleton::Singleton()
{ //... perform necessary instance initializations
}

usage

Singleton *p1 = Singleton::Instance();
Singleton *p2 = p1->Instance();
Singleton & ref = * Singleton::Instance();

2 תגובות:

Anonymous said...

http://www.naughter.com/

bimba at May 10, 2009 at 10:24 AM said...

thank you!

this is just what i need for a university project.

bimba.

Post a Comment

 
Home | About | Link | Link
Simple Proff Blogger Template Created By Herro | Inspiring By Busy Bee Woo Themes