码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2017-10-16 21:41:49      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:syn   饿汉式   ret   return   zed   tin   static   blog   vol   

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

 

单例模式

标签:syn   饿汉式   ret   return   zed   tin   static   blog   vol   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!