单例模式实现案例

我们实现了一个电脑窗口类,众所周知,电脑窗口只有一个,不可以进行拷贝,复制,因此我们使用单例模式

#include <iostream>
#include <limits>
#include <cstdlib>
using namespace std;

class Screen {
private:
	unsigned int _width;
	unsigned int _height;
	
	Screen(unsigned int width, unsigned int height) {
		_width = width;
		_height = height;
	};
	Screen() {    //不能通过常规手段生成对象

	}
	~Screen() {
		delete instance;
		instance = nullptr;
	}
public:
	static Screen* instance;        //单例
	Screen(const Screen&) = delete;       //同时不允许用拷贝的方式进行赋值
	Screen& operator= (const Screen&) = delete; 

	static Screen* getInstance() {
		if (instance == nullptr) {
			instance = new Screen();
		}
		return instance;
	}

	static Screen* getInstance(int theWidht, int theHeight){

		if (instance == nullptr) {
			instance = new Screen();
		}

		if ((theWidht > 0 && theWidht <= 1920) && (theHeight > 0 && theHeight <= 1080)) {
			instance->_width = theWidht;
			instance->_height = theHeight;
		}
		else {
			instance->_width = 1920;
			instance->_height = 1080;
		}

		return instance;
	}
	unsigned int getWidth() const{
		return _width;
	}
	unsigned int getHeight() const{
		return _height;
	}
};

Screen* Screen::instance = nullptr;

int main() {
	int width, height;
	Screen* screen = 0;
	cin >> width >> height;
	screen = Screen::getInstance(width, height); //进行初始化操作,初始化instance,只有这么一个实例
	screen = Screen::getInstance();
	cout << screen->getWidth() << " " <<
		screen->getHeight() << endl;


	system("PAUSE");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值