饿汉式:
在类加载的时候就初始化创建单例对象,线程安全,但存在的问题就是无论使用与否都创建对象,造成内存浪费
代码实现:
/*
饿汉式
*/
public class HungrySingleton {
private HungrySingleton(){}
private static HungrySingleton instance = new HungrySingleton();
public static HungrySingleton getInstance(){
return instance;
}
public static void main(String[] args) {
HungrySingleton obj1 = HungrySingleton.getInstance();
HungrySingleton obj2 = HungrySingleton.getInstance();
System.out.println(obj1 == obj2);
}
}
懒汉式:
在外部调用时才会去加载,线程不安全,可以通过线程加锁来保证安全,但效率较低
代码实现:
/**
* 懒汉式
*/
public class LazySingleton {
private LazySingleton(){}
private static LazySingleton instance;
public static LazySingleton getInstance(){
if (instance == null){
instance = new LazySingleton();
}
return instance;
}
public static void main(String[] args) {
LazySingleton obj1 = LazySingleton.getInstance();
LazySingleton obj2 = LazySingleton.getInstance();
System.out.println(obj1 == obj2);
}
}
双重校验锁:
使用volatile以及多重检查,来减小锁范围,提升效率。
/**
* 双重校验锁
*/
public class DoubleCheckSingleton {
private DoubleCheckSingleton(){}
private volatile static DoubleCheckSingleton instance;
public static DoubleCheckSingleton getInstance(){
synchronized (DoubleCheckSingleton.class){
if (instance == null){
instance =new DoubleCheckSingleton();
}
}
return instance;
}
public static void main(String[] args) {
DoubleCheckSingleton obj1 = DoubleCheckSingleton.getInstance();
DoubleCheckSingleton obj2 = DoubleCheckSingleton.getInstance();
System.out.println(obj1 == obj2);
}
}
静态内部类:
解决饿汉式(内存浪费)和懒汉式(线程不安全)的问题。
代码实现:
/**
* 静态内部类
*/
public class StaticSingleton {
private StaticSingleton(){}
public static StaticSingleton getInstance(){
return StaticClass.instance;
}
private static class StaticClass{
private static final StaticSingleton instance = new StaticSingleton();
}
public static void main(String[] args) {
StaticSingleton obj1 = StaticSingleton.getInstance();
StaticSingleton obj2 = StaticSingleton.getInstance();
System.out.println(obj1 == obj2);
}
}