方法一: namespace DesignPattern_Singleton { // class Singleton class Singleton { protected: Singleton() {} static Singleton *_instance ; private: Singleton(const Singleton&) ; Singleton& operator=(const Singleton&) ; } ; Singleton* Singleton::_instance = NULL ;
// class ConcreteSingleton class ConcreteSingleton : public Singleton { public: static Singleton* Instance() ; protected: ConcreteSingleton() {} } ;
Singleton* ConcreteSingleton::Instance() { (_instance == NULL) ? _instance = new ConcreteSingleton() : 0 ; return _instance ; } }
客户端代码: { using namespace DesignPattern_Singleton ; Singleton *p = ConcreteSingleton::Instance() ; }
方法二: namespace DesignPattern_Singleton { // class Singleton class Singleton { protected: Singleton() {} private: Singleton(const Singleton&) ; Singleton& operator=(const Singleton&) ; } ;
// class ConcreteSingleton class ConcreteSingleton : public Singleton { public: static Singleton* Instance() { static ConcreteSingleton _instance ; return &_instance ; } protected: ConcreteSingleton() {} } ; }
客户端代码: { using namespace DesignPattern_Singleton ; Singleton *p = ConcreteSingleton::Instance() ; }
方法三: namespace DesignPattern_Singleton { template < class T > class Singleton { public: static T* Instance() { static T _instance ; return &_instance ; } protected: Singleton() {} private: Singleton(const Singleton &) ; Singleton& operator=(const Singleton&) ; } ;
class ConcreteSingleton : public Singleton< ConcreteSingleton > {} ; }
客户端代码 { using namespace DesignPattern_Singleton ;
ConcreteSingleton *p = ConcreteSingleton::Instance() ; }
|