Main Page | Namespace List | Class Hierarchy | Compound List | File List | Namespace Members | Compound Members | File Members | Related Pages

csingletonmanager.h File Reference

#include <assert.h>

Go to the source code of this file.

Compounds

class  CSingletonFactory
class  CSingletonManager


Detailed Description

Defines the CSingletonManager and CSingletonFactory template classes, used for creating polymorphic singleton frameworks.

CSingletonManager is a template for a polymorphic singleton whose class can change at runtime, which is something that (as far as I know) a conventional singleton can't do, but it's something I needed in order to support something akin to "pluggable" device drivers. This setup differs from the standard singleton in a number of ways.

Standard singleton static methods (get_instance(), etc) are NOT part of the class that we want "singletoned". Instead, we have a "manager" that takes care of the one instance of the singleton class.

Let's say we have a class A that we want to be "singletoned" with this kind of system. We define a private constructor for this class so that no one can create it, and we give it no static methods, but we do give it one friend class, which we'll call AFactory.

   class A {
     friend class AFactory;
     A();
   public:
     void do_something();
   };

AFactory is a method with a public constructor and one private method called make_singleton(), which returns a new instance of A. Then we define a class called AManager as its friend. This is the "manager" class I described earlier.

   class AFactory {
     friend class AManager;
     A *make_singleton() { return new A(); }
   public:
     AFactory();
   };

AManager is a class that contains only static member variables and methods, and is fairly similar to a standard singleton. The only major difference in operation is that it has an intialization method which takes an AFactory as a parameter.

   class AManager {
     static A *unique_instance;
  
   public:
     static void init(AFactory &aFactory) {
       unique_instance = aFactory.make_singleton();
     }

     static A &deinit() { delete unique_instance; }
  
     static A &get_instance() { return *unique_instance; }
   };

That's basically how it works. The CSingletonManager is basically a templatized version of the AManager in this example, and the CSingletonFactory is a templatized version of the AFactory.

If you would like to see a very simple example of this, check out the CTimerSystem class and its related classes. Here we have the following setup:

(note that sdl_ctimer.cpp just defines the static variable that stores the pointer to the unique instance.)

Advantages of this setup:

Disdvantages of this setup:

Definition in file csingletonmanager.h.


Generated on Wed Aug 27 11:58:42 2003 for GFW by doxygen 1.3.3