trollixx

C++ Singleton Template

Jun 25th, 2011
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. # Normally, you want just 1 instance of your Settings class
  2. # Here standart template for this behavior is provided:
  3.  
  4. -------------------------------header file-----------------------------------
  5. #include "core/config.h"
  6. #include "core/settings.h"
  7.  
  8. #define $CLASSNAME$Settings ($CLASSNAME$::instance())
  9. #define $CLASSNAME$Settings_writeable (const_cast<$CLASSNAME$*>($CLASSNAME$::instance()))
  10.  
  11. class $CLASSNAME$ : public Settings
  12. {
  13. public:
  14.     static const $CLASSNAME$ * instance();
  15.  
  16.     // put here your setting fields
  17.  
  18. private:
  19.     $CLASSNAME$();
  20.     static $CLASSNAME$ *self;
  21.  
  22. protected:
  23.     // implementation of pure virtuals from base class
  24.     void settingsChanged();
  25.     void resetGui();
  26.     void flushSettings();
  27. };
  28. -------------------------------source file-----------------------------------
  29. $CLASSNAME$ *$CLASSNAME$::self = 0;
  30.  
  31. $CLASSNAME$::$CLASSNAME$() :
  32.     Settings("$CLASSNAME$")
  33. {
  34.     TRACE;
  35.  
  36.     // put here some initialization, probably reading settings from ini files,  using
  37.     // methods from base class
  38.  
  39. }
  40.  
  41. const $CLASSNAME$ * $CLASSNAME$::instance()
  42. {
  43.     if(!self)
  44.         self = new $CLASSNAME$;
  45.     return self;
  46. }
  47.  
  48. void $CLASSNAME$::settingsChanged()
  49. {
  50.     TRACE;
  51.     // this method is called, when user selects Ok in settings dialog -
  52.     // it means, settings in GUI are accepted and have to be applied
  53. }
  54.  
  55. void $CLASSNAME$::resetGui()
  56. {
  57.     TRACE;
  58.     // this method is called, when user clicks Cancel in settings dialog -
  59.     // it means, settings in GUI are discarded, and class has to fill GUI with old settings
  60. }
  61.  
  62. void $CLASSNAME$::flushSettings()
  63. {
  64.     TRACE;
  65.     // this method is called, when application terminates, and all settings have
  66.     // to be flushed on disk
  67. }
Advertisement
Add Comment
Please, Sign In to add comment