简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM