单例模式的根本是保证对象唯一性
1.不让其他程序创建该类对象。
2.在本类中创建一个本类对象。
3.对外提供方法,让其他程序获取这个对象。
饿汉式
public class SingleEHanShi {
private SingleEHanShi(){}
private static SingleEHanShi singleEHanShi = new SingleEHanShi();
public static SingleEHanShi getInstance(){
return singleEHanShi;
}
}
class TestDemo{
public static void main(String[] args) {
SingleEHanShi singleEHanShi = SingleEHanShi.getInstance();
SingleEHanShi singleEHanShi1 = SingleEHanShi.getInstance();
System.out.println(singleEHanShi == singleEHanShi1);
}
}
懒汉式(线程安全)
普通的懒汉式存在线程安全问题
public class SingleLanHanShi {
private SingleLanHanShi(){}
//延迟加载
private static SingleLanHanShi singleLanHanShi = null;
public static SingleLanHanShi getInstance(){
if (singleLanHanShi == null){
synchronized(SingleLanHanShi.class){
if (singleLanHanShi == null){
/*这里是两行代码,可能会出现线程安全问题,这里可以加锁避免安全问题*/
singleLanHanShi = new SingleLanHanShi();
}
}
}
return singleLanHanShi;
}
}
class TestDemo1{
public static void main(String[] args) {
SingleLanHanShi singleLanHanShi = SingleLanHanShi.getInstance();
SingleLanHanShi singleLanHanShi1 = SingleLanHanShi.getInstance();
System.out.println(singleLanHanShi == singleLanHanShi1);
}
}