First, UML diagram
Second, the concept
Singleton mode: guarantees that a class has only one instance and provides a global access point to access him. [DP]
Usually we can have a global variable that makes an object accessible, but it doesn't prevent you from instantiating multiple objects. One of the best ways is to have the class itself responsible for protecting its only instance. This class ensures that no other instance can be created, and that he can provide a way to access the instance.
Third, note:
Using singleton mode, you can only guarantee that an object within a thread is not created more than once, and that there is no guarantee of multithreading. Therefore, the need to consider multi-threaded words, it is necessary to use locks.
Iv. implementation of UML
Header file Singleton.h:
#ifndef singleton_h#define singleton_h#include <afx.h>class singleton{private:static Singleton* instance;//Critical Zone To prevent multiple instances of multithreading from generating static critical_section m_sec; Singleton () {}public:static critical_section* getlock () {return &m_sec;} Static Singleton *getinstance () {//Double lock if (instance==null) {entercriticalsection (&m_sec); if (instance==null) Instance=new Singleton (); LeaveCriticalSection (&m_sec);} return instance;}; #endif
Customer Single Code:
#include <iostream> #include "Singleton.h"//static members define singleton* singleton::instance=0 outside the class body; critical_section singleton::m_sec=critical_section (); void Main () {//Initialize critical section initializecriticalsection (Singleton:: Getlock ()); singleton* singleton1=singleton::getinstance (); singleton* singleton2=singleton::getinstance ();//delete critical section deletecriticalsection (Singleton::getlock ()); if (singleton1 ==singleton2) std::cout<< "Two objects are the same instance. "<<std::endl;system (" pause ");}
Big talk design pattern C + + implementation-21st chapter-Singleton mode