创建型模式-单例模式

实现方式

  • 饿汉式:线程安全,调用效率高,不支持延时加载
public class Singleton {
    private static Singleton instance = new Singleton();  
    
    private Singleton(){
    }
    
    public static Singleton  getInstance(){
        return instance;
    }
}

  • 懒汉式:线程安全,调用效率较低,支持延时加载
public class Singleton {
    private static Singleton instance;  
    
    private Singleton(){
    }

    public static  synchronized Singleton getInstance(){
        if(instance==null){
            instance = new Singleton();
        }
        return instance;
    }
}

/**
 * 懒汉式单例模式(防止反射和反序列化漏洞)
 */
public class Singleton implements Serializable {

    private static Singleton instance;  
    
    private Singleton(){ 
        // 反射漏洞
        if(instance!=null){
            throw new RuntimeException();
        }
    }
    
    public static  synchronized Singleton  getInstance(){
        if(instance==null){
            instance = new Singleton();
        }
        return instance;
    }
    
    //反序列化时,定义readResolve()则直接返回此方法指定的对象。
    private Object readResolve() throws ObjectStreamException {
        return instance;
    }
    
}
  • 静态内部类式:线程安全,调用效率高,可延时加载
public class Singleton {
    
    private static class SingletonClassInstance {
        private static final Singleton instance = new Singleton();
    }
    
    private Singleton(){
    }
    
    //方法没有同步,调用效率高!
    public static Singleton getInstance(){
        return SingletonClassInstance.instance;
    }
    
}
  • 枚举式:线程安全,调用效率高,不支持延时加载,可天然防止反射与序列化漏洞
public enum Singleton {
    //枚举元素就是单例对象!
    INSTANCE;
    
    //添加自己需要的操作!
    public void singletonOperation(){
    }
}
  • 双重检测锁:JVM底层内部模型问题,偶尔会出现问题,
public class Singleton{ 

  private static Singleton instance = null; 

  public static Singleton getInstance() { 
    if (instance == null) { 
      Singleton sc; 
      synchronized (Singleton.class) { 
        sc = instance; 
        if (sc == null) { 
          synchronized (Singleton.class) { 
            if(sc == null) { 
              sc = new Singleton(); 
            } 
          } 
          instance = sc; 
        } 
      } 
    } 
    return instance; 
  } 
  private Singleton() { 
  } 
}

你可能感兴趣的:(创建型模式-单例模式)