所谓双例形式,便是采纳1定的圆法包管零个硬件体系,对某个类只存正在1个工具虚例,且该类只提求1个与失其工具虚例的圆法。
- 饥汉式双例形式(动态变质)
/**
* 饥汉式
* 线程平安
*/
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getIntance(){
return instance;
}
}
- 饥汉式双例形式(动态代码块)
/**
* 饥汉式
* 线程平安
*/
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton(){}
public static Singleton getIntance(){
return instance;
}
}
- 懒汉式线程没有平安的双例形式:
/**
* 懒汉式
* 线程没有平安
*/
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getIntance(){
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
- 懒汉式线程平安的双例形式:(但因为异步器,每一次皆要异步,效力低)
/**
* 懒汉式
*/
public class Singleton {
private static Singleton instance;
private Singleton(){}
/**
* 减进异步器弄定
*/
public static synchronized Singleton getIntance(){
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
- (拉荐利用)动态外部类的圆式虚现双例形式(线程平安,懒减载)
// 中部类被装载时,外部类否能没有会坐刻装载
// getInstance挪用时,外部类合初装载
// 装载时是 线程平安 的,以是动态变质只会始初化1次
public class Singleton {
private Singleton(){}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getIntance(){
return SingletonInstance.INSTANCE;
}
}
- (拉荐利用)列举圆式虚现双例形式(线程平安,非懒减载,防反序列化)
enum Singleton {
INSTANCE;
public void sayOK() {
System.out.println("ok");
}
}
转自:https://www.cnblogs.com/gradyblog/p/15357901.html
更多文章请关注《万象专栏》
转载请注明出处:https://www.wanxiangsucai.com/read/cv3601