1

I'm trying to connect to the database only one time by using singleton pattern, below is my implementation.

Will it guarantee that the m_connector.connect(); is only called once?

Is using singleton the best solution?

class ConnectionManager
{
public:

  static ConnectionManager& getManager()
  {
    static ConnectionManager manager;
    return manager;
  }

  void reconnect();
  Connection getConnection();

private:
  ConnectionManager():m_connector("port")
  {
    m_connector.connect();
  };
  ConnectionManager(ConnectionManager const&);
  void operator=(ConnectionManager const&);

  Connector m_connector;
};
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
user3828398
  • 495
  • 3
  • 9
  • 18

1 Answers1

0

Will it guarantee that the m_connector.connect(); only run once?

No.

The only fact that's guaranteed in that case of implementation (aka as Scott Meyer's Singleton) is that the constructor of ConnectionManager is called once and only once.

  static ConnectionManager& getManager()
  {
    static ConnectionManager manager;
    return manager;
  }

It will be called as soon ConnectionManager::getManager(); is called the first time.

The constructor in turn calls m_connector.connect()

  ConnectionManager():m_connector("port")
  {
    m_connector.connect();
  };

There's no guarantee that

    m_connector.connect();

won't be called from any other parts of your code. The declaration of

  void reconnect();

even implies that somehow.

But well, it's all under your control.

If the constructor is the only function that calls m_connector.connect();, and you are worrying about thread safety, you shouldn't need to. It's guaranteed to be thread safe with the current standard.


Is using singleton the best solution?

Probably not. Nothing should hinder you to revise your decisions later, and to decide you actually need to have more ConnectionManager instances.

Any other part of your code that will use ConnectionManager::getManager(); is tightly coupled to that singleton class, and it will become hard to refactor your code if it should be made more generic.

This kind of hardcoding a DB connection

  ConnectionManager():m_connector("port")
                               // ^^^^^^

extremely narrows the scalability of your application.


I personally would make it a class, with the appropriate constructor parameters to create a connection, and having a public (abstract) interface implemented, that can be accessed via a factory function, or some of the other Creational Design Patterns dedicated to instance creation, and nothing else.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190