首页 > 其他 > 详细

单例模式

时间:2017-10-16 21:02:29      阅读:204      评论:0      收藏:0      [点我收藏+]

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() {  
    }  
}  

 

单例模式

原文:http://www.cnblogs.com/leiqjl/p/7678229.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!