设计模式:单件模式

参加了多场笔试,在笔试题目中偶尔会问什么单件模式。在网上搜了之后了解到这是设计模式中的一种设计方法。单件模式可用于消除全局这样的需求。

Q.什么是单件模式?

A.单件模式是一种用于确保整个应用程序中只有一个实例,且这个实例所占资源在整个应用程序中是共享时的程序设计方法。

Q在面向对象中如何设计出只有一个实例的对象呢?

A.每个对象的产生都要调用构造函数,对构造函数进行限制有可能能达到要求。因此,把构造函数设计为私有或保护类型。

Q.私有的构造函数如何构造一个对象呢?

A.声明成一个类的静态变量,变量声明时可以调用私有的构造函数或者在有权限调用私有函数的函数内部构造该对象(对象内的函数有权限,友元有权限)

明白了这些,看看如何通过全局变量的方法构建一个满足单件模式的类吧。

class singleton
{
	static singleton s;
	int i;
	singleton(int x): i(x){};//构造函数全屏蔽掉
	singleton(const singleton &);
	singleton & operator=(singleton &);
public:
	 static singleton& instance() //返回对象
	 {
	 	return s;
 	}
	int getValue()
	{
		return i;
	}
	void setValue(int x)
	{
		i = x;
	}
};
singleton singleton::s(44); //这里可以对对象进行初始化
测试

int main()  
{  
	singleton & s=singleton::instance();//获得对象
	cout << s.getValue()<<endl;
	singleton & s1=singleton::instance();//获得对象
	s1.setValue(20);
	cout << s.getValue()<<endl;
        return 0;
}

这样的设计是不是很漂亮?还有更漂亮的,咱们试着去掉那句单独的初始化。

我们知道,局部静态变量会被初始化一次,并且仅当函数被调用时才会生成该变量。该变量自从被生成就会一直存在着。这样可以满足需求。

设计如下

class singleton
{
	int i;
	singleton(int x): i(x){};
	singleton(const singleton &);
	singleton & operator=(singleton &);
public:
 	static singleton& instance() 
 	{
 		static singleton s(44);
 		return s;
 	}

	int getValue()
	{
		return i;
	}
	void setValue(int x)
	{
		i = x;
	}
};
测试

int main()  
{  
	singleton & s=singleton::instance();//获得对象
	cout << s.getValue()<<endl;
	singleton & s1=singleton::instance();//获得对象
	s1.setValue(20);
	cout << s.getValue()<<endl;
        return 0;
}

上面的方法并没有限制只创建一个对象。上面的技术支持创建有限个对象的对象池。考虑构造静态对象数组。解决了吧。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值