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