首页 > 其他 > 详细

设计模式-单例模式

时间:2018-02-23 18:25:15      阅读:178      评论:0      收藏:0      [点我收藏+]

懒汉式


/**
 * 懒汉式,线程不安全需要使用 synchronized做同步
 */
class Single{
    private static Single single = null;
    private Single(){

    }
    public static synchronized Single getInstance(){
        if(single == null){
            single = new Single();
        }
        return single;
    }

    //线程安全第二种方式
    public static  Single getInstance2(){
        //静态方法  因此不能使用this  a b c  每次并发调用都需要等待,因此效率不高
        synchronized (Single.class) {
            if (single == null) {
                single = new Single();
            }
        }
        return single;
    }

    //线程安全第二种方式优化
    public static  Single getInstance3(){
        //静态方法  因此不能使用this  a b c  每次并发调用都需要等待,因此效率不高
        if(single == null) {
            synchronized (Single.class) {
                if (single == null) {
                    single = new Single();
                }
            }
        }
        return single;
    }
}

饿汉式


/**
 * 饿汉式  线程安全
 */
class Single2{  //效率底下,当Single2.say()调用时那么single 就会被初始化,可以使用内部类来解决这个问题,因为类只有在调用的时候才会被加载
    private static Single2 single = new Single2();
    private Single2(){
    }
    public static  Single2 getInstance(){
        return single;
    }

    public static  String say(){
        return "....";
    }
}


/**
 * 饿汉式  线程安全 使用内部类优化
 */
class Single3{
    private static class SingleWrap{
        private static Single3 single = new Single3();
    }

    private Single3(){
    }
    //即使调用say single也不会被初始化
    public static  Single3 getInstance(){
        return SingleWrap.single;
    }
    public static  String say(){
        return "....";
    }
}

设计模式-单例模式

原文:https://www.cnblogs.com/mf001/p/8462632.html

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