[转]【创建型】 之 单件模式

/***********************************************
* 【创建型】 之 单件模式
*
*
*摘自c++ 编程思想 第2卷 384页  2010-12-30
************************************************/
#include <iostream>
using namespace std;
class Singleton
{
 private:
 static Singleton s;

 int i;
 Singleton (int x):i(x) { };
  
 Singleton& operator=(Singleton&); //disabled
 Singleton (const Singleton&); 	   //disabled
 
 public:
	static Singleton  &instance(){
		return s;
	}
	int getValue(){
		return i;
	}
	void setValue(int x){
		i =x;
	}
}

Singleton::s(47);

int main(){

	Singleton& s = Singleton::instance();
	cout <<s.getValue()<<endl;
	
	Singleton& s2 = Singleton::instance();
	s2.setValue(9);
	cout << s.getValue()<<endl;
}
posted @ 2010-12-30 21:44  网络小虫  阅读(222)  评论(0编辑  收藏  举报