关闭

单件

108人阅读 评论(0) 收藏 举报
分类:
#include<iostream>
using 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(50);
int main()
{
	Singleton& s=Singleton::instance();
	cout<<s.getValue()<<endl;
	Singleton& s2=Singleton::instance();
	s2.setValue(9);
	cout<<s.getValue()<<endl;
}

#include<iostream>
using namespace std;
class Singleton{
	int i;
	Singleton(int x):i(x){ }
	void operator=(Singleton&);
	Singleton(const Singleton&);
public:
	static Singleton& instance(){
		static Singleton s(47);
		return s;
	}
	int getValue(){ return i;}
	void setValue(int x) { i=x;}	
}; 
int main()
{
	Singleton& s=Singleton::instance();
	cout<<s.getValue()<<endl;
	Singleton& s2=Singleton::instance();
	s2.setValue(9);
	cout<<s.getValue()<<endl; 
}
//如果两个单件彼此依赖,就会产生一个特别有趣的情况 
class Singleton1{
	Singleton1(){}
	public:
		static Singleton1& ref(){
			static Singleton1 single;
			return single;
		}
};
class Singleton2{
	Singleton1& s1;
	Singleton2(Singleton1& s):s1(s){}
	public:
		static Singleton2& ref(){
			static Singleton2 single(Singleton1::ref());
			return single;
		}
		Singleton1& f(){
			return s1;
		}
};
int main()
{
	Singleton1& s1=Singleton2::ref().f();
}

#include<iostream>
using namespace std;

template<class T> class Singleton{
	Singleton(const Singleton&);
	Singleton& operator=(const Singleton&);
protected:
	Singleton(){}
	virtual ~Singleton(){}
public:
	static T& instance(){
		static T theInstance;
		return theInstance;
	}
}; 
class MyClass:public Singleton<MyClass>{
	int x;
protected:
	friend class Singleton<MyClass>;
	MyClass() { x=0;}
public:
	void setValue(int n) { x=n;}
	int getValue() const { return x;}
};
int main()
{
	MyClass& m=MyClass::instance();
	cout<<m.getValue()<<endl;
	m.setValue(1);
	cout<<m.getValue()<<endl;
return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8542次
    • 积分:201
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:18篇
    • 译文:1篇
    • 评论:1条
    最新评论