一、单例模式
单例模式模式能够保证一个类的对象实例只有一个,具体的做法是将类的构造函数设置为私有或者受保护,然后再提供一个静态接口,通过该接口可以创建或者获取该类的唯一实例对象,具体的代码如下表示:
class Singleton
{
private:
Singleton(){};
public:
static Singleton* GetInstance()
{
if( m_p == NULL )
m_p = new Singleton();
return m_p;
}
private:
static Singleton* m_p;
};
Singleton* Singleton::m_p = NULL;
上述代码是普通的单例模式的实现方式。
为了让类具有多态行为,可以引入继承方式,具体如下:
class Singleton_1
{
protected:
Singleton_1(){}
public:
virtual void show(){}
static Singleton_1* GetInstance( const char* name )
{
if( m_p == NULL )
{
if( strcmp( name, "SingletonA" ) == 0 )
{
m_p = new SingletonA();
}
else if( strcmp( name, "SingletonB" ) == 0 )
{
m_p = new SingletonB();
}
}
return m_p;
}
private:
static Singleton_1* m_p;
};
Singleton_1* Singleton_1::m_p = NULL;
class SingletonA : public Singleton_1
{
friend class Singleton_1;//this is important for the parent class enable to create the instance of the derive class
private:
SingletonA(){}
public:
virtual void show()
{
cout<<"SingletonA"<<endl;
}
};
class SingletonB : public Singleton_1
{
friend class Singleton_1;//this is important for the parent class enable to create the instance of the derive class
private:
SingletonB(){}
public:
virtual void show()
{
cout<<"SingletonB"<<endl;
}
};
在上述代码中,将单例模式的基类作为派生类的友元类,这样使得在基类中可以创建构造函数被私有化的派生类实例,这样就能够实现根据需要创建对应的单例对象。
上述代码只是提供思路,具体的实现还需要考虑很多细节问题,如内存释放问题,多线程共享问题等。