设计模式之---单例模式

1.恶汉模式

所谓恶汉模式,即类在加载的时候就完成了实例化(类在初始化时就创建了对象),避免线程同步问题。

实现原理:创建静态实例,对外提供静态的方法

1.静态常量   【可用】

public class Singleton {

    private final static Singleton INSTANCE = new Singleton();
    
    private Singleton() {
        
    }
    public static Singleton getInstance(){
        return INSTANCE;
    }
}

  

2.静态代码块 【可用】

public class Singleton {

    private static Singleton instance;
    
    static{
        instance = new Singleton();
    }
    //构造方法私有
    private Singleton() {
        
    }
    public static Singleton getInstance(){
        return instance;
    }
}

 

2.懒汉模式

1.线程不安全    【不可用】

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

2.线程安全,同步方法 【不推荐用】

public class Singleton {

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

3.线程安全,同步代码块  【不可用】

public class Singleton {

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

4.线程安全,双重检查(即代码块前后都判断是否为空)【可用】

public class Singleton {

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

5.静态内部类 【可用】

 1 public class Singleton {
 2     
 3     private Singleton() {}
 4     
 5     private static class SingletonInstance{
 6         private final static Singleton INSTANCE = new Singleton();
 7     }
 8     
 9     public static Singleton getInstance(){
10         return SingletonInstance.INSTANCE;
11     }
12 }

6.枚举 【可用】

public enum Singleton {
    INSTANCE;
    public void whateverMethod() {

    }
}
原文地址:https://www.cnblogs.com/xiaozhijing/p/8423519.html