After reading the examples of three singleton patterns on Thinking in C++, I have a preliminary understanding of it.
Code first:
Example 1:
#include<iostream>
using namespace std;
class Singleton{
static Singleton s;//Create a private static instance (object) step1
int i;
Singleton(int x):i(x){}
Singleton& operator=(Singleton&);// disallowed will not be called
Singleton(const Singleton&);//disallowed will not be called
public:
static Singleton& instance(){return s;}//public static member function, call the only channel of s step2
int getValue(){return i ;}
void setValue(int x){i=x;}
};
Singleton Singleton::s(47);//Initialization, an error will be reported if not initialized
//cout<<&s<<endl;
int main()
{
Singleton& s =Singleton::instance();
cout<<s.getValue()<<endl;
Singleton& s2=Singleton::instance();
cout<<&s<<endl<<&s2<<endl;//The address is the same, it can be seen that there is only one instance of Singleton
s2.setValue(9);
cout<<s.getValue()<<endl;
return 0;
}
Example 2:
#include<iostream>
#include<math.h>
using namespace std;
class Singleton
{
int i;
Singleton(int x):i(x){}
void operator=(Singleton&);
Singleton(const Singleton&);
public:
static Singleton& instance(){
static Singleton s(111);
return s;
}//Create a static instance in a static member function. Because it is static, it is already created at compile time, and multiple functions will not be created because of multiple calls. object
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;
}
Example 3:
#include<iostream>
using namespace std;
template<class T>
class Singleton{
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
protected:
Singleton(){}
virtual~ Singleton(){}//虚析构函数,防止内存泄漏
public:
static T& instance(){
static T theInstance;
return theInstance;
}
};
class MyClass:public Singleton<MyClass>{
int x;
protected:
friend class Singleton<MyClass>;
MyClass(){x=0;}
public:
void setValue(int n){x=n;}
int getValue()const{return x;}
};
int main()
{
MyClass& m=MyClass::instance();
cout<<m.getValue()<<endl;
m.setValue(1);
cout<<m.getValue()<<endl;
}//相当于单件模板
https://blog.csdn.net/windboyzsj/article/details/2790485
//About the C++ singleton mode to release the object
https://www.cnblogs.com/cxjchen/p/3148582.html
//Singleton mode multithreading
http://www.cnblogs.com/qicosmos/p/3145019.html
//Singleton mode template plus advanced version