单例模式---饿汉式
Java代码:
class Sign{
//类加载时初始化,不延迟加载,类加载时是线程安全的 效率低
private static Sign s = new Sign();
//私有化构造器
private Sign(){}
//线程安全 ,效率高
public static Sign getInstance(){
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++代码:
#include <stdlib.h>
#include <stdio.h>
class Singlton {
private:
Singlton(){}
public:
static Singlton* GetInstance() {
return sln;
}
private:
static Singlton* sln;
};
// 饿汉式
Singlton* Singlton::sln = new Singlton();
int main(){
Singlton* pSln = Singlton::GetInstance();
Singlton* pSln2 = Singlton::GetInstance();
if (pSln2 == pSln){
printf("pSln2 == pSln \n");
}
else {
printf("pSln2 != pSln \n");
}
system("pause");
return 0;
}
总结:
1.构造器私有化
2.(Java)类加载时初始化类对象,线程安全的 (C++)sln属于全局变量区
3.函数直接调用线程安全