views:

146

answers:

3

Hi ,

I have 3 interface classes IVideo , IAudio , IGPIO and three other classes that will implement those interface: Video_impl , Audio_impl , GPIO_impl.

Things is simple so far.

But then ,I want all those object to be singleton. Here are the questions:

Is it a good idea to abstract an Interface ISingleton , so that Video_impl , Audio_impl , GPIO_impl (or IVideo , IAudio , IGPIO ?) can inherit from it?

I was thinking of implement it in following way. Is it recommended? I think there must be better ways.

//Isingleton.hpp
template <class T>
class ISingleton
{
public:
virtual T *getInstance() = 0;

};

class IGPIO
{
public:
virtual int SelectAudioInput() = 0;
};

class GPIO_impl : public IGPIO, public ISingleton<IGPIO>
{
public:
    IGPIO *getInstance();
    int SelectAudioInput() ;
private:
    IGPIO *instance;
};
+1  A: 

I don't see the benefit here. You still have to implement the getInstance() method in your derived class. So you've introduced templates and multiple inheritance, but haven't really gained anything. The only small gain I can see is you're making all your singleton's share a common method, but this is such a common pattern that I don't think that's a real gain.

Glen
+3  A: 

I would recommend reading Alexandrescu's "Modern C++ Design". In it, among many other things, he designs a fully-fledged singleton template and thinks through many of the issues, such as when it should be destroyed, whether it should resurrect after being destroyed because it is needed during the destruction of other singletons, and all that good stuff.

Kaz Dragon
Indeed the question of lifetime are tricky and should not be underestimated, I like the Phoenix policy :)
Matthieu M.
+1  A: 

Your singleton won't work. You cannot use a virtual method to return the instance as this can only be called with an instance. You need at the very least a static method, or an intermediate object that implements the singleton.

You should read up on the implementation of singletons in C++ if you plan to generalise it like this. However my advice for all library code is to create the clean simple implementations you need first. In the singleton case this would be simply implement it as a static method with no inheritance. Then and only when you have implemented it a number of times and fully understand all the motivations and details for an abstract implementation should you create a library for it. Creating libraries too early is one of the largest causes of bugs and unmaintainable code.

iain