// Purpose.  Singleton design pattern demo.
//
// Discussion.  Make the class of the single instance object responsible
// for creating, maintaining, and guarding the object.  The client has
// global access.  It is not possible to do an "end-run" around the single
// instance constraint.  And, the instance is never created if the
// resource is never needed.


#include <iostream.h>


class Singleton {
public:
   int getValue()
   {
      return _value;
   }
   void setValue( int val )
   {
      _value = val;
   }
   static Singleton* instance()
   {
      if ( ! _instance )
         _instance = new Singleton;
      return _instance;
   }
protected:
   Singleton() : _value( -999 ) { }
private:
   int                _value;
   static Singleton* _instance;  // this is the declaration only
};

// This is the definition for _instance.  This is where the memory for the
// static data member (i.e. C++ class-scoped global) is allocated.  If this
// statement is missing, C++ generates a link error.
Singleton* Singleton::_instance = 0;


main()
{
   // Singleton myInstance;  constructor `Singleton::Singleton()' is protected

   cout << "main: Singleton is " << Singleton::instance()->getValue() << endl;
   Singleton::instance()->setValue( 42 );
   cout << "main: Singleton is " << Singleton::instance()->getValue() << endl;
}

// main: Singleton is -999
// main: Singleton is 42

