Singleton mode: guarantees that a class has only one instance and provides a global access point to access it
First version:
#include <iostream>using namespace Std;class singleton{ static Singleton s; You can declare a reference to an object of the class itself in the class definition or to an object of that class, or you can use static to decorate the object int i; Singleton (int x): I (x) {}; Singleton (const singleton&);//do not allow copying of singleton& operator= (singleton&);//Do not allow assignment public:static singleton& instance () {return s;} int GetValue () {return i;} void SetValue (int x) {i=x;}}; Singleton singleton::s (n); int main () {singleton& s=singleton::instance (); Cout<<s.getvalue () <<endl ; singleton& s2=singleton::instance (); S2.setvalue (9); Cout<<s.getvalue () <<endl;//singleton s3= Singleton::instance (); The error declaration copy constructor is private and does not allow copying of getchar (); return 0;}
A second version:
#include <iostream>using namespace Std;class singleton{int i; Singleton (int x): I (x) {}; Singleton (const singleton&);//Do not allow copy singleton& operator= (singleton&);//Do not allow assignment public:static Singleton & Instance () { static Singleton s (88);//static object creation within the member function implements Singleton mode return s;} int GetValue () {return i;} void SetValue (int x) {i=x;}}; int main () {singleton& s=singleton::instance (); Cout<<s.getvalue () <<endl; singleton& s2=singleton::instance (); S2.setvalue (9); Cout<<s.getvalue () <<endl;//singleton s3= Singleton::instance (); The error declaration copy constructor is private and does not allow copying of getchar (); return 0;}
Single-Case mode