background image

C++遇到 IOS 应用开发—LRUCache 缓存

    考虑到缓存实现多数使用单例模式,这里使用 C++的模版方式设计了一个 Singlton 基类,
这样以后只要继承该类,子类就会支持单例模式了。其代码如下:

[cpp]
//
//  SingltonT.h
//

#ifndef SingltonT_h
#define SingltonT_h
#include <iostream>
#include <tr1/memory>
using namespace std;
using namespace std::tr1;
template <typename T>
class Singlton {
public:
static T* instance();
~Singlton() {
cout << “destruct singlton” << endl;
}
protected:
Singlton();
//private:
protected:
static std::tr1::shared_ptr<T> s_instance;
//Singlton();
};

template <typename T>
std::tr1::shared_ptr<T> Singlton<T>::s_instance;

template <typename T>
Singlton<T>::Singlton() {
cout << “construct singlton” << endl;
}

template <typename T>
T* Singlton<T>::instance() {
if (!s_instance.get())