目录
Singleton 是对全局变量的取代策略。
<1>.作用:保证一个类只能有一个实例,并提供一个全局唯一的访问点。
<2>.仅有一个实例:通过类的静态成员变量来体现。
<3>.提供访问它的全局访问点:访问静态成员函数来体现。
<1>.它有一个指向唯一实例的静态指针,并且是私有的;
<2>.它有一个公有的函数,可以获取这个唯一的实例,并且在需要的时候创建该实例;
<3>.它的构造函数是私有的,这样就不能从别处创建该类的实例。
<4>.Singleton不可以被实例化,因此我们将其构造函数声明为protected或者直接声明为private。
- #include
- using namespace std;
-
- class Singleton{
- private:
- //静态成员,保存对象的唯一实例
- static Singleton* pInstance;
- //私有化构造函数,使其无法在类外实例化
- Singleton();
-
- public:
- static Singleton* Instance();
- void Destroy();
- };
-
-
- Singleton* Singleton::pInstance = NULL;
-
- //构造函数
- Singleton::Singleton(){
- cout<< "Singleton..." << endl;
- }
-
- Singleton* Singleton::Instance(){
- if(NULL == pInstance)
- pInstance = new Singleton();
-
- return pInstance;
- }
-
- void Singleton::Destroy(){
- delete pInstance;
- pInstance = NULL;
- cout<< "Destroy..." << endl;
- }
-
-
- int main(){
- //通过全局访问点获取实例
- Singleton* ps = Singleton::Instance();
- ps->Destroy();
-
- return 0;
- }
- #include
- #include
- using namespace std;
-
- template<typename T>
- class Singleton {//定义类Singleton
- static T* c_instance;
- public:
- static T* GetInstance();
- private:
- int m_count;
- };
-
- template<typename T>
- T* Singleton
::c_instance = NULL;//定义c_instance全局变量 -
- template<typename T>
- T* Singleton
::GetInstance() {//实现单例模式函数 - if(c_instance == NULL)
- c_instance = new T();
-
- return c_instance;
- }
-
- class SObject{
- //友元类,当前类SObject需要使用Singleton类单例模式,所以定义友元类
- friend class Singleton
; - // SObject(const SObject&);
- // SObject& operator= (const SObject&);
-
- SObject(){
- printf("xxx----->len = %d\n",__LINE__);
- }
- public:
- void print(){
- cout << "this = " << this << endl;
- }
- };
-
- int main(){
- //将SObject类传入单例模式的类模板,然后调用GetInstance()获取类的实例化
- SObject* s = Singleton
::GetInstance(); -
- s->print();//打印this指针的地址,查看当前实例化是否成功
- return 0;
- }