#include <stdio.h>
c++ 23种设计模式之单例模式
//适用情况:1、唯一实
namespace DesignPattern_Singleton
{
//第一种
class Singleton
{
public:
static Singleton*Instance()
{
static Singleton _instance;
return &_instance;
}
void showInfo()
{
printf(" 我是单例模式!\n");
}
protected:
Singleton(){}//屏蔽构造函数
private:
Singleton(const Singleton&);
Singleton& operator=(const Singleton &);
};
//第二种
class ConcreteSingleton
{
public:
static ConcreteSingleton *getInstance();
void showInfo()
{
printf("success!\n");
}
protected:
ConcreteSingleton(){}
~ConcreteSingleton(){}
static ConcreteSingleton *_instance;
};
ConcreteSingleton *ConcreteSingleton::_instance=NULL;
ConcreteSingleton *ConcreteSingleton::getInstance()
{
if(_instance==NULL)
{
_instance=new ConcreteSingleton();
}
return _instance;
}
//第三种
template <class T>
class MySingleton
{
public:
static T* getInstance()
{
static T _instance;
return &_instance;
}
void showInfo(){
printf("test success \n");
};
protected:
MySingleton(){}
~MySingleton(){}
};
class SubMySingleton :public MySingleton<SubMySingleton>
{
};
}
void main()
{
using namespace DesignPattern_Singleton;
Singleton *p=Singleton::Instance();
p->showInfo();
ConcreteSingleton *pSingleton=ConcreteSingleton::getInstance();
pSingleton->showInfo();
SubMySingleton *sub=SubMySingleton::getInstance();
sub->showInfo();
}
c++23种设计模式之单例模式
最新推荐文章于 2024-08-16 10:33:33 发布