最近,在学习设计模式,由于比较熟悉C++,所以,都是用C++实现的。
由于没看过《设计模式》之类的书,都是从网上搜的资料,看的代码,看完之后,自己又重新实现了一遍。
由于是干androd的,所以这个单例模式是参考的android实现的.
位置:android4.4.2\442\system\core\include\utils\Singleton.h
android4.4.2\442\frameworks\native\services\sensorservice\SensorService.cpp
头文件
//singleton.h
#ifndef __SINGLETON__
#define __SINGLETON__
#include "Mutex_Demo.h" //看我前面的文章,有这部分的代码
template<typename TYPE>
class Singleton {
public:
static TYPE& getInstance(){
Synchronize synch(m_mutex);//多线程进行线程同步
std::cout<<"getInstance()"<<std::endl;
TYPE* instance = sInstance;
if (instance == NULL) {
instance = new TYPE();
sInstance = instance;
}
return *instance;
}
protected:
Singleton(){}
~Singleton(){}
private:
static MutexLock m_mutex;
static TYPE * sInstance;
};
//初始化静态变量用的
#define SINGLETON_STTIC_INSTANCE(TYPE) \
template<> TYPE* Singleton<TYPE>::sInstance(NULL); \
template<> MutexLock Singleton<TYPE>::m_mutex;
#endif
cpp文件
#include <iostream>
#include "Mutex_Demo.h"
#include "singleton.h"
using namespace std;
class SensorDevice:public Singleton<SensorDevice>{
friend class Singleton<SensorDevice>;//友元是为了让父类访问,当前类中的私有构造函数
public:
void show(){cout<<"SensorDevice::show()"<<endl;}
private:
SensorDevice(){}//必须为私有
};
SINGLETON_STTIC_INSTANCE(SensorDevice) //初始化static变量
使用方法:
int main() {
SensorDevice& sd = SensorDevice::getInstance();//获取
sd.show();
return 1;
}
结果:
getInstance()
SensorDevice::show()
1.必须将构造函数私有化,这样就不能通过new来私自取得对象
2在类中创建一个本类静态对象
3 提供一个静态的方法可以得到该对象