Design pattern C + + implementation 17: Singleton mode

Source: Internet
Author: User

Before we learn the singleton pattern, we have to know about the use of static. I have the following summary article by reviewing the relevant information and blog. http://blog.csdn.net/shiwazone/article/details/45815615.

Singleton mode (Singleton): guarantees that a class has only one instance and provides a global access point to access it.

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 preserving its only instance. This class guarantees that no other instance can be created, and it can provide a way to access the instance:

#ifndef singleton_h#define singleton_h#include<iostream>class Singleton{private:singleton () {}// The privatization constructor makes it impossible to construct an instance statically Singleton * singleton;//static variable class garbo//is responsible for the destruction of the new Singleton,{public:~garbo () {if ( Singleton! = nullptr) {std::cout << destory! \ n "; Delete singleton;//deletes singleton}}};static Garbo garbo;//when the program is about to end, the Garbo variable will be called, and the Garbo class's destructor public:static Singleton * getinstance ()//provide an interface to create an object {if (singleton = = nullptr)//By judging if there is an instance, return the address if it exists, so that only one instance exists singleton = new Singleton; return singleton;}; Singleton * Singleton::singleton = nullptr;//static type initialization format:< data type > < class name;:: static Data name = initialization value #endif
#include <iostream> #include "Singleton.h" using namespace Std;int Main () {Singleton *s1 = singleton::getinstance () ; Singleton *s2 = Singleton::getinstance (); if (S1 = = s2) cout << "Two objects are the same instance. \ n "; else cout <<" Two pairs are different instances. \ n "; return 0;}


Design mode C + + implementation 17: 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.