ITeye博客

单实例Singleton设计模式

plutoblog · 2011-10-15 02:19 · 设计模式 · 编程语言 · Markdown

(一)C++实现方式:

 

class OnlyOne
{
	int data;

public:
	static OnlyOne& Instance()
	{
		static OnlyOne uniqueInstance;
		return uniqueInstance;
	}
public:
	int GetData(){return data;}
protected:
	OnlyOne():data(100){}	//构造函数为protected,也可以是private,但子类不能调用该构造函数
	OnlyOne(OnlyOne&){}
};

 

若要求返回值非静态,则借助友元函数:

namespace OnlyOne
{
	class RealOnlyOne
	{
	protected:
		int data;

	public:
		friend RealOnlyOne& Instance();

	protected:
		RealOnlyOne(): data(100){}
		RealOnlyOne(const RealOnlyOne &){}
	};

	RealOnlyOne& Instance()
	{
		static RealOnlyOne uniqueInstance;
		return uniqueInstance;
	}
}

 

 

也可以使用c++的模板,实现代码重用:

 

template<class T>
class Singleton
{
public:
	static T& Instance()
	{
		static T uniqueInstance;
		return uniqueInstance;
	}
};

class OnlyOne: public Singleton<OnlyOne>
{
	friend class Singleton<OnlyOne>;
	int data;

public:
	int GetData(){return data;}
protected:
	OnlyOne():data(100){}	//构造函数为protected,也可以是private,但子类不能调用该构造函数
	OnlyOne(OnlyOne&){}
};

 创建单实例方式示例:

 

int main()
{
	cout<<OnlyOne::Instance().GetData()<<endl;
	return 0;
}

 

(二)java实现方式,考虑了多线程同步

 

public class OnlyOne{
	private static volatile OnlyOne uniqueInstance = null;
	
	private OnlyOne(){
		
	}
	
	public static OnlyOne getInstance(){
		if(uniqueInstance == null){
			synchronized(OnlyOne.class){
				if(uniqueInstance == null){
					uniqueInstance = new OnlyOne();
				}
			}
		}
		
		return uniqueInstance;
	}
};

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。