I am building a C ++ application and I have several utility objects that all my classes should use. These are things like a logging object, a global state object, a DAL object, etc.
Until that moment, I passed all these objects as references to my class constructors.
For example:
class Honda: public Car { public: Honda (const GlobalState & state, const log & logger, const DAL & dal); ... private: const GlobalState & my_state; const Log & my_logger; const DAL & my_dal; }
, , , , .
, - , , ( ) , .
? !
: . Injection Dependency.
Locator. ( ), .
: , , , . , . , , .
, , - ( ). .
GlobalState, Log, DAL:
class GlobalState { public: static GlobalState& getInstance(); protected: GlobalState(); GlobalState(const GlobalState&); GlobalState& operator= (const GlobalState&); private: static GlobalState* p_instance; }; static GlobalState* GlobalState::p_instance = NULL; /*static*/ GlobalState& getInstance() { // TODO: acquire lock if multi-threaded if (!p_instance) { // first time? p_instance = new GlobalState(); // create sole instance } // TODO: release lock if multi-threaded return *p_instance; // sole instance }
, ,
Honda::MyMethod() { ... const GlobalState& my_state = GlobalState::getInstance(); ... }
( ) ++- (, ..)
, - - , . , Singleton . , factory , Singleon. Singleton .
, , .
, Vlad R, ( ), , :
GlobalState::getInstance()
, , , -, .
. , , singleton , , , (.. singleton ). , .
, : (, , , ), , . , , , , ; , , ( , ).
: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12
, , :
:
.