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

多种单例模式

时间:2017-04-13 14:58:38      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:on()   single   highlight   单例模式   nbsp   let   线程安全   class   hold   

//1 懒汉,线程不安全
public class Singleton {
    private static Singleton instance = null;
    private Singleton(){}

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

        return instance;
    }   
}

//2 懒汉,线程安全
public class Singleton {
    private static Singleton instance = null;
    private Singleton(){}

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

        return instance;
    }
}

//3 饿汉
public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){}

    public static Singleton getInstance(){      
        return instance;
    }
}

//4 静态内部类
public class Singleton {
    private static class SingletonHolder {
        public static Singleton instance = new Singleton();
    }
    private Singleton(){}

    public static Singleton getInstance(){      
        return Singleton.SingletonHolder.instance;
    }
}

//5 枚举
public class Singleton {

    private Singleton(){}

    public static Singleton getInstance(){      
        return Single.instance.getInstance();
    }

    private static enum Single {
        instance;

        private  Singleton single;
        //JVM会保证此方法绝对只调用一次
        private Single(){
            single = new Singleton();
        }

        public Singleton getInstance(){
            return single;
        }
    }
}

//6 双重校验锁
public class Singleton {

    private static volatile Singleton instance = null;
    private Singleton(){}


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

 

多种单例模式

标签:on()   single   highlight   单例模式   nbsp   let   线程安全   class   hold   

原文地址:http://www.cnblogs.com/liu-king/p/6703761.html

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