A single-instance pattern of Python design patterns

Source: Internet
Author: User
Tags sin

The singleton pattern appears as a substitute for " global Variables " . So it has the characteristics of global variables: globally visible, throughout the lifetime of the application, to ensure that in the program run, a class only one instance, so the constructor in the class is usually not expected to be called

Python:

Class single (object): Instance = None#def __init__ (self):p ass#def getinstance (self): if single.instance = = None: Single.instance = single () return single.instance#def printself (self): if single.instance! = None:print single.instances = Single () S1 = s.getinstance () s2 = s.getinstance () s1.printself () s2.printself () </span>

C++:

Single.h

Ifndef __single_h#define __single_hclass single{private:static single *instance; Single ();p ublic:static single* getinstance (); void Printself ();}; #endif


Single.cpp

#include "Single.h" #include <iostream>single* single::instance = NULL; Single::single () {}single* single::getinstance () {if (!instance) instance = new Single;return instance;} void Single::p rintself () {if (instance) Std::cout << instance << Std::endl;}


#include "Single.h" int main () {single::getinstance ()->printself (); Single *sin = Single::getinstance (); sin->printself (); return  0;}


A single-instance pattern of Python design patterns

Related Article

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.