Search code examples
c++design-patternssingletonmixins

making a SingletonMixin class in c++


I have four classes, let's call S1, S2, S3 and S4. These class are singletons; each one have a getInstance and a finalize method - and an instance private variable-.

Now, to avoid repeting the finalize and getInstance methods I'm trying to make a SingletonMixin class, something like:

template<class T> class SingletonMixin
{
    public:
        static T* getInstance();
    private:
        static T* instance;

};

The problem here is: how can instance the singleton clasess and keep their constructor private?


Edit

(clarification)

I mean, how can I do that:

template<class T> T* SingletonMixin<T>::instance = 0;
template<class T> T* SingletonMixin<T>::getInstance()
{
    if (instance == 0)
    {
        instance = T();
    }
    return instance;
};

but with private T construct T()


Thanks!


Solution

  • The problem: If you make (de)constructors private, the Singleton base class cannot generate an instance.

    However:

    friend class SingletonMixin<Foo>;
    

    is your friend.