我们实现了一个电脑窗口类,众所周知,电脑窗口只有一个,不可以进行拷贝,复制,因此我们使用单例模式
#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;
}