What is the best way to handle multiple object dependencies in C ++?

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.

+5
7

Locator. ​​ ( ), .

: , , , . , . , , .

, , - ( ). .

+6

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();
  ...
}

( ) ++- (, ..)

+11

, - - , . , Singleton . , factory , Singleon. Singleton .

+2

, , .

, Vlad R, ( ), , :

GlobalState::getInstance()

, , , -, .

+1

. , , singleton , , , (.. singleton ). , .

, : (, , , ), , . , , , , ; , , ( , ).

+1

, , :

  • .
  • Singletons.
  • .
  • ( )

:

.

0

All Articles