设计模式

Singleton模式

2017-11-15  本文已影响0人  老练子丶2017

先来一发最简单的压压惊

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

优点:保证唯一性 只能通过唯一的接口访问

上一篇 下一篇

猜你喜欢

热点阅读