第62课.单例模板
1.单例模式
概念:定义一个类,使得这个类最多只能创建一个对象。(单例对象在系统的生命周期中都是存在的,所以单例对象在整个系统的运行中不释放)
思路:
a.将构造函数的访问属性设置为private
b.定义instance并初始化为NULL
c.当需要使用对象时,访问instance值
空值:创建对象,并用instance标记
非空值:返回instance标记的对象
eg:
#include <iostream>
#include <string>
using namespace std;
class SObject
{
static SObject* c_instance; // 静态指针
SObject(const SObject&); // private 拷贝函数,使得函数不能进行拷贝
SObject& operator = (const SObject&); // private 重载=使得,函数不能能进行赋值
SObject () // private 使得对象不能被外界创建
{
}
public:
static SObject* GetInstance(); // 静态函数 用于创建对象
void print() // 打印 对象的地址
{
cout << "this = " << this << endl;
}
};
SObject* SObject::c_instance = NULL;
SObject* SObject::GetInstance()
{
if(c_instance == NULL)
{
c_instance = new SObject();
}
return c_instance;
}
int main()
{
SObject* s = SObject::GetInstance();
SObject* s1 = SObject::GetInstance();
SObject* s2 = SObject::GetInstance();
s->print();
s1->print();
s2->print();
return 0;
}
2.单例类模板
Singleton.h
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
template < typename T >
class Singleton
{
static T* c_instance;
public:
static T* GetInstance();
};
template < typename T >
T* Singleton<T>::c_instance = NULL;
template < typename T >
T* Singleton<T>::GetInstance()
{
if(c_instance == NULL)
{
c_instance = new T();
}
return c_instance;
}
#endif /* _SINGLETON_H_ */
main
#include <iostream>
#include <string>
#include "Singleton.h"
using namespace std;
// 注释的部分在模板中实现了,这样可以避免每次都重复去定义这两个部分,这样
// 只需要每次确保类的构造,拷贝,=为private即可
class SObject
{
// static SObject* c_instance;
friend class Singleton<SObject>; // 注意这一步,使用了友元。这样可以使用Singleton中到成员
SObject(const SObject&);
SObject& operator = (const SObject&);
SObject ()
{
}
public:
// static SObject* GetInstance();
void print()
{
cout << "this = " << this << endl;
}
};
// SObject* SObject::c_instance = NULL;
#if 0
SObject* SObject::GetInstance()
{
if(c_instance == NULL)
{
c_instance = new SObject();
}
return c_instance;
}
#endif
int main()
{
SObject* s = Singleton<SObject>::GetInstance();
SObject* s1 = Singleton<SObject>::GetInstance();
SObject* s2 = Singleton<SObject>::GetInstance();
s->print();
s1->print();
s2->print();
return 0;
}