⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 singleton_lab.cpp

📁 设计模式
💻 CPP
字号:
// Purpose.  Singleton design pattern lab.
//
// Problem.  The application would like a single instance of globalObject
// to exist, and chooses to implement it as a global.  Globals should
// always be discouraged.  Additionally, any code that references the
// global object, has to first check if the pointer has been initialized,
// and initialize it if it has not.
//
// Assignment.
// o Replace the global variable globalObject with a private static data member.
// o Provide the pattern-specified accessor function.
// o Provide for initialization and init testing in the GlobalObject class.
// o All client code should now use the Singleton accessor function instead of
//   referencing the globalObject variable.
// o Remove any client code dealing with globalObject initialization.
// o Guarantee that the GlobalObject class cannot be instantiated.

#include <iostream.h>


class GlobalObject {
public:
	static GlobalObject*  Instance() 
	{
		return &_instance;
	}
	int  getValue()              { return value_; }
	void setValue( int val )     { value_ = val; }
private:
	int  value_;
	static GlobalObject _instance;	
	GlobalObject(int) : value_( 0 ) { }
};

GlobalObject GlobalObject::_instance(0);

void foo( GlobalObject *globalObject ) {
   cout << "foo: globalObject's value is " << globalObject->getValue() << endl;
}
void bar( GlobalObject *globalObject ) {
   globalObject->setValue( 42 );
   cout << "bar: globalObject's value is " << globalObject->getValue() << endl;
}


void main( void ) {
   foo( GlobalObject::Instance() );
   bar( GlobalObject::Instance() );
   cout << "main: globalObject's value is " << GlobalObject::Instance()->getValue() << endl;
}

// foo: globalObject's value is 0
// bar: globalObject's value is 42
// main: globalObject's value is 42

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -