三种常见的单例模式懒汉式
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if (instance==null){
instance = new Singleton();
}
return instance;
}
}
饿汉式
public class Singleton1 {
private static Singleton1 instance = new Singleton1();
private Singleton1(){}
public static Singleton1 getInstance(){
return instance;
}java单例模式懒汉和饿汉
}
双重锁
public class Singleton2 {
private volatile static Singleton2 instance;
private Singleton2(){}
public static Singleton2 getInstance(){
if (instance==null){
synchronized (Singleton2.class){
if (instance==null){
instance = new Singleton2();
}
}
}
return instance;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。