单例模式---懒汉式
Java代码:
class Sign{
private static Sign s; //不初始化
//私有化构造器
private Sign(){}
//线程安全synchronized
//延迟加载
public static synchronized Sign getInstance(){
if(s == null){
s = new Sign();
}
return s;
}
}
public class Test{
public static void main(String[] args) {
Sign s1 = Sign.getInstance();
System.out.println(s1);
Sign s2 = Sign.getInstance();
System.out.println(s2);
}
}
测试结果:
javaTestpack.Fil@139a55
javaTestpack.Fil@139a55
C++代码:
class Singlton {
private:
Singlton(){}
public:
static Singlton* GetInstance() { // 多线程不安全,需加锁
if (nullptr == sln)
{
sln = new Singlton();
}
return sln;
}
static void ReleaseInstance() {
if (nullptr != sln){
delete sln;
sln = nullptr;
}
}
private:
static Singlton* sln;
};
Singlton* Singlton::sln = nullptr;
int main(){
Singlton* pSln = Singlton::GetInstance();
Singlton* pSln2 = Singlton::GetInstance();
if (pSln2 == pSln){
printf("pSln2 == pSln \n");
}
else {
printf("pSln2 != pSln \n");
}
Singlton::ReleaseInstance();
system("pause");
return 0;
}
总结:
1.构造器私有化
2.(JAVA)静态类引用延迟创建加载
3.注意线程安全性