singleton_lab.cpp

来自「设计模式」· C++ 代码 · 共 55 行

CPP
55
字号
// 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 + =
减小字号Ctrl + -
显示快捷键?