创建型模式-单例模式

2019-02-11  本文已影响0人  未知角色

实现方式

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(){
    }
}
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() { 
  } 
}
上一篇 下一篇

猜你喜欢

热点阅读