public class Singleton {
//私有构造方法
private Singleton() {}
//创建对象
private static Singleton instance = new Singleton();
//公共获取方法
public static Singleton getInstance() {
return instance;
}
}
public class Singleton {
//私有构造方法
private Singleton() {}
//声明
private static Singleton instance;
//在静态代码块中进行赋值
static {
instance = new Singleton();
}
//公共访问
public static Singleton getInstance() {
return instance;
}
}
饿汉式缺点:只要进行了类加载,对象就创建出来了,容易造成内存的浪费
public class Singleton {
//私有构造方法
private Singleton() {}
//声明
private static Singleton instance;
//访问
public static Singleton getInstance() {
//保证单例
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
//私有构造方法
private Singleton() {}
//声明
private static Singleton instance;
//访问
public static synchronized Singleton getInstance() {
//保证单例
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
线程安全&&线程不安全方式缺点:读操作效率较低
public class Singleton {
//私有构造方法
private Singleton() {}
//volatile 保证有序性
private static volatile Singleton instance;
public static Singleton getInstance() {
//首先判断是否为空,不为空直接返回,减少不必要抢占锁
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton {
private Singleton() {}
//静态内部类
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
//就是这么简单
public enum Singleton {
INSTANCE;
}
OVER(∩_∩)O~