单例模式的C++版本实现

2017-09-17  本文已影响0人  鲨漠里的鱼

单例模式的意图:保证一个类仅有一个实例,并且提供一个访问她的全局访问点。

第一种形式:

#includeusing namespace std;

class Singleton {

static Singleton s;

int i;

Singleton(int x) :i(x) {};

//把复制构造函数和“=”操作符也设为私有,防止复制和拷贝

Singleton & operator = (Singleton&);//不允许赋值

Singleton(const Singleton&);//不允许拷贝

public:

static Singleton& instance() { return s; }

int getValue() { return i; }

void setValue(int x) { i = x; }

};

Singleton Singleton::s(47);//定义静态成员s

int main()

{

Singleton& s = Singleton::instance();

cout << s.getValue() << endl;

Singleton & s2 = Singleton::instance();

s2.setValue(9);

cout << s.getValue() << endl;

return 0;

}

请你写出一个单例模式来。

好,这个题目很简单,相信大家都能很快的写出来(写出来立即编译没有错误—当时去IBM面试时候的要求)。

请大家放心,面试官是不会就这么放过你滴。

会分别问你:怎么才能更节省资源?多线程情况下怎么样?双重检查方式的单例模式?还有其它的实现方式么?

一步步进逼,不会让你大喘气滴。

大家来试试,只要写出下面四种方式的就可以了:

A:单线程下单例模式;

B:简单修改A中代码,实现多线程下的单例模式;

C:双重检查的单例模式;

D:还有其它实现方式么?

上一篇 下一篇

猜你喜欢

热点阅读