views:

65

answers:

3

Hi guys:

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!

A: 

Does the following not work?

class Foo : public SingletonMixin<Foo>
{
};
FredOverflow
@FredOverflow: It doesn't work, the base class cannot call the derived class' constructor / destructor if they are protected / private. You have declare the base class as a `friend` to be able to do it.
Praetorian
+1  A: 

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

However:

friend class SingletonMixin<Foo>;

is your friend.

nob
There are no deconstructors, only destructors.
Georg Fritzsche
A: 

Singletons and inheritence mix together very badly. This is because the fundamental statement about a Singleton is: "there can only ever be one instance of this class", whereas the existence of child classes implies that there is at least the possibility of different instances. You should almost certainly refactor this to make those four classes not Singletons.

DJClayworth