Singleton that is not available worldwide

I just thought the best way is to get rid of the public static getInstance () in Singleton. I do not want my Singleton classes to be accessible from every point in my program.

I thought that I have a static create () function that creates one object and returns it, but you cannot call this method twice.

But it is not very elegant for me. Than I would have to make a statement or throw an exception in case create () is called a second time.

Is there any other way to achieve what I want?

+3
source share
3 answers

, " ". : . ++ , . , .

, , . ( , , ). , :

#include <stdexcept>

// inherit from this class (privately) to ensure only
// a single instance of the derived class is created
template <typename D> // CRTP (to give each instantiation its own flag)
class single_instance
{
protected: // protected constructors to ensure this is used as a mixin
    single_instance()
    {
        if (mConstructed)
            throw std::runtime_error("already created");

        mConstructed = true;
    }

    ~single_instance()
    {
        mConstructed = false;
    }

private:
    // private and not defined in order to
    // force the derived class be noncopyable
    single_instance(const single_instance&);
    single_instance& operator=(const single_instance&);

    static bool mConstructed;
};

template <typename T>
bool single_instance<T>::mConstructed = false;

, :

class my_class : private single_instance<my_class>
{
public:
    // usual interface (nonycopyable)
};

int main()
{
    my_class a; // okay
    my_class b; // exception
}
+3

Singleton , , .

. , .

- . Singleton ( GoF) singleton ( ' ").

+2

You can protect your method getInstance()and allow access through ads friend. You will have to manually "white" classes with access getInstance()by adding an ad friend.

class Singleton {
protected:
  static Singleton* getInstance() { return Singleton::s_instance_; }
  // Allow access to SingletonUser
  friend class SingletonUser;
private:
  Singleton() { }
  static Singleton* s_instance_;
};

class SingletonUser {
public:
  void doStuff() {
    // Fails if not a friend of Singleton
    Singleton* s = Singleton::getInstance();
  }
};
+1
source

Source: https://habr.com/ru/post/1769394/


All Articles