单例模式

1.饿汉式

1 public class Singleton {
2     private Singleton(){}
3     private static Singleton instance = new Singleton();
4     public static Singleton getInstance() {
5         return instance;
6     }
7 }

2.饿汉式

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

3.双重检测

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

4.静态内部类

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

5.枚举

public enum Singleton {  
    INSTANCE;  
    public void method() {  
    }  
}  

 

posted @ 2017-10-16 18:32  leiqjl  阅读(98)  评论(0编辑  收藏  举报