单例设计模式

来源:互联网 发布:windows用airplay 编辑:程序博客网 时间:2024/05/22 00:29

方式一: 饿汉式 简单直接,不用

class Single{    private static final Single s = new Single();    private Single(){}    public static Single getSingle(){        return s;    }}

方式二: 懒汉式

(1) 存在安全问题

class Single_{    private static  Single_ s = null;    private Single_(){}    public static Single_ getSingle_(){        if(s == null){            s = new Single_();        }        return s;    }}

(2) 安全,但有效率问题

class Single_1{    private static  Single_1 s = null;    private Single_1(){}    public static Single_1 getSingle_1(){        synchronized(Single_1.class){           //加锁            if(s == null){                s = new Single_1();            }        }        return s;    }}

(3) 安全、效率高

class Single_2{    private static  Single_2 s = null;    private Single_2(){}    public static Single_2 getSingle_2(){        if(s == null){                          //再加一层循环,解决效率问题            synchronized(Single_2.class){       //加锁                if(s == null){                    s = new Single_2();                }            }        }        return s;    }}
0 0
原创粉丝点击