先来一发最简单的压压惊
singleton.h:
#ifndef _SINGLETON_H
#define _SINGLETON_H
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton* getInstance();
protected:
Singleton() {};
private:
static Singleton* instance_;
};
#endif // _SINGLETON_H
singleton.cpp
#include "singleton.h"
Singleton* Singleton::instance_ = NULL;
Singleton* Singleton::getInstance() {
if (instance_ == NULL) {
instance_ = new Singleton();
}
return instance_;
}
int main()
{
Singleton* sing = Singleton::getInstance();
return 0;
}
编译:make singleton
优点:保证唯一性 只能通过唯一的接口访问
网友评论