Big talk design pattern C + + implementation-21st chapter-Singleton mode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.