Design patterns are the focus of programming. Often reviewed during an interview, the Singleton model is the simplest, most common, mostly main mode. So most of the interviews are singleton design patterns for test exams.
Let's take a look at how the singleton pattern is implemented (c + + code):
#include <iostream>using namespace Std;class Singleton {public:static singleton* Instance ();p Rotected:singleton ();p rivate:static singleton* _instance; }; singleton* singleton::_instance=0; Singleton::singleton () {cout<< "Singleton ..." <<endl;}; Singleton*singleton::instance () {if (_instance==0) {_instance=new Singleton ();} return _instance;} int main (int argc,char* argv[]) {singleton* sgn=singleton::instance (); return 0;}The constructor for the singleton type must be protected to ensure that the type cannot be instantiated, and the static member function instance is used to instantiate the type. Because the function is static, each invocation is the same instance. This ensures that the singleton type can be instantiated once.
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
C + + Singleton