// Copyright (C) 2012-2013 ChaosForge / Kornel Kisielewicz // http://chaosforge.org/ // // This file is part of NV Libraries. // For conditions of distribution and use, see copyright notice in nv.hh /** * @file singleton.hh * @author Kornel Kisielewicz epyon@chaosforge.org * @brief singleton pattern */ #ifndef NV_SINGLETON_HH #define NV_SINGLETON_HH #include namespace nv { /** *singleton *@brief Represents an accessible static object that will only have one instance. */ template class singleton { private: static T *singleton_; ///< Pointer to the instance of this object type. protected: /** *Creates the single instance if one doesn't already exist. */ singleton() { assert(!singleton_); singleton_ = static_cast(this); } /** *Destroys the instance. */ ~singleton() { assert(singleton_); singleton_ = 0; } public: /** *Checks to see if the instance exists. * *@returns True if this singleton has an instance assigned, false otherwise. */ static bool is_valid() { return singleton_ != 0; } /** *Returns the pointer to the instance. * *@returns The pointer to the instance. */ static T *pointer() { assert(singleton_); return singleton_; } /** *Returns the object referenced by this singleton. */ static T &reference() { assert(singleton_); return *singleton_; } }; template T* singleton::singleton_ = 0; /** *auto_singleton *@brief Represents a singleton that automatically creates an instance if one doesn't already exist. */ template class auto_singleton : public singleton { public: /** *Returns the pointer to the instance. Makes an instance if one doesn't already exist. */ static T *pointer() { if ( !singleton::is_valid() ) { new T(); } return singleton::pointer(); } /** *Returns the object referenced by this singleton. Makes an instance if one doesn't already exist. */ static T &reference() { if ( !singleton::is_valid() ) { new T(); } return singleton::reference(); } }; } // namespace nv #endif // NV_SINGLETON_HH