* 单例设计模式4类 : 饿汉式, 懒汉式, 内部类 , 枚举
饿汉式[可用]
- 优点 : 在类的加载时完成实例化,避免了线程同步问题
- 缺点: 由于在类的加载就实例化, 没有实现 懒加载, 造成了资源的浪费
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {};
public static Singleton getInstance() {
return instance;
}
}
懒汉式[线程不安全,不可用]
在多线程情况下, 是不安全的
class Singleton1 {
private static Singleton1 instance;
private Singleton1() {};
public static Singleton1 getInstance() {
if( instance == null) {
instance = new Singleton1();
}
return instance;
}
}
懒汉式[线程安全, 效率低, 不推荐用]
- 缺点, 每次申请实例 都需要进行同步, 然而只有第一次才需要实例化,
后面的只执行return语句, 同步机制效率低
class Singleton3 {
private static Singleton3 instance;
private Singleton3() {}
public static synchronized Singleton3 getInstance() {
if( instance == null)
{
instance = new Singleton3();
}
return instance;
}
}
懒汉式双重校验锁[推荐用]
- 优点: 懒汉式变种,属于懒汉式中最好的写法,保证了:延迟加载和线程安全 效率较高
class Singleton4{
private static Singleton4 instance;
private Singleton4() {};
public static Singleton4 getInstance() {
if( instance == null) {
synchronized(Singleton4.class) {
if(instance == null) {
instance = new Singleton4();
}
}
}
return instance;
}
}
内部类 [线程安全, 延迟加载,效率高]
- 内部类的实现方式与 饿汉式类型, 都是 采用类加载机制来保证实例化时只有一个线程, 从而保证线程安全
不同于饿汉式的类加载机制, 静态内部类在 Singleton5类加载时不会立即实例化,实现了lazy-loading - 而是在调用 getInstance方法时才会加载 内部类实例化, 类的静态属性只会在第一次加载类的时候初始化,
- JVM 保证了线程的安全
class Singleton5 {
private Singleton5() {};
public static InnerSingleton getInstance () {
return InnerSingleton.instance;
}
private static class InnerSingleton {
private static InnerSingleton instance = new InnerSingleton();
private InnerSingleton() {};
}
}
枚举[推荐使用]
enum SingletonEnum {
instance;
private SingletonEnum() {}
public void method(){
}
}