单例模式
作者:互联网
做些笔记。
引用https://blog.csdn.net/weixin_40834464/article/details/82958187
//单例模式
public class SingleTon {
//私有得构造方法
private SingleTon(){}
//饿汉 类加载的时候就加载完成
private static final SingleTon singleTon = new SingleTon();
//
public static SingleTon getSingleTon(){
return singleTon;
}
}
//双重校验锁
public class SingleTon2 {
private SingleTon2(){};
//同步机制
//volatile 禁止指令重排序
private volatile static SingleTon2 singleTon2=null;
//双重校验锁先判断 uniqueInstance 是否已经被实例化,如果没有被实例化,那么才对实例化语句进行加锁
public static SingleTon2 getSingleTon2() {
if(singleTon2==null){
synchronized(SingleTon2.class){
if (singleTon2==null) {
singleTon2 = new SingleTon2();
}
}
}
return singleTon2;
}
//对整个方法都加锁,同时只有一个线程能访问,
// public static synchronized SingleTon2 getInstance(){
// if (singleTon2==null){
// singleTon2 = new SingleTon2();
// }
// return singleTon2;
// }
}
/**
* 静态内部类写法
*/
public class SingleTon3 {
private SingleTon3(){};
//方问静态内部类时 才实例化SingleTon3
private static class SingleTonHolder{
private static final SingleTon3 singleTon3 = new SingleTon3();
}
public static SingleTon3 getSingleTon3(){
return SingleTonHolder.singleTon3;
}
}
/**
*枚举类singleTon
*/
public class EnumSingleton {
private EnumSingleton(){};
public static EnumSingleton getEnumSingleTon(){
return SingleTon4.INSTANCE.getSingleTon();
}
private static enum SingleTon4{
INSTANCE;
private EnumSingleton singleTon;
private SingleTon4(){
singleTon = new EnumSingleton();
};
public EnumSingleton getSingleTon(){
return singleTon;
}
}
public static void main(String[] args) {
EnumSingleton enumSingleton1 = EnumSingleton.getEnumSingleTon();
EnumSingleton enumSingleton2 = EnumSingleton.getEnumSingleTon();
System.out.println("enumSingleTon1 = enumSingleTon2?"+(enumSingleton1 == enumSingleton2));
}
}
标签:EnumSingleton,private,static,模式,单例,singleTon2,SingleTon2,public 来源: https://blog.csdn.net/qq_39249471/article/details/110680049