Semmu
Semmu

Reputation: 133

Is this C++ singleton pattern and method exposure a good practice?

I would like to have a singleton class and expose some of its methods publicly, that work directly on the instance. Is the code below a good pattern?

class Singleton
{
public:
    static Singleton& get()
    {
        // the easiest way to implement a singleton class

        static Singleton instance;

        return instance;
    }

    static void publicMethodOne()
    {
        // "redirecting" the call to the instance itself

        get().instancePublicMethodOne();
    }

    static void publicMethodTwo()
    {
        // "redirecting" the call to the instance itself

        get().instancePublicMethodTwo();
    }

private:
    Singleton() {}
    Singleton(const Singleton& s) {}
    Singleton& operator=(const Singleton& s) {}

    void instancePublicMethodOne()
    {
        // do stuff
    }

    void instancePublicMethodTwo()
    {
        // do stuff
    }

    void privateMethodOne()
    {
        // privately do stuff
    }
};


// call from outside
Singleton::publicMethodOne();

This basically redirects every static and public method call to the instance, and every static and public method has a pair method inside the instance.

EDIT: I want to use singleton pattern, that is sure. My question is whether this pattern to expose instance methods globally is good or not.

Upvotes: 1

Views: 236

Answers (1)

justanothercoder
justanothercoder

Reputation: 1890

Compare these two calls yourself:

Singleton::publicMethodOne();
Singleton::get().publicMethodOne();

You just put the call to Singleton::get inside this static methods. It doesn't make much sense to do so. It would only inflate code.

Upvotes: 1

Related Questions