Android设计模式之单例模式

来源:互联网 发布:淘宝 诚信荣誉 编辑:程序博客网 时间:2024/06/05 07:05

单例模式注意事项

1、静态化私有变量

2、私有化构造函数

3、公共静态的构造方法


几个例子:


/**=============================== 单例懒汉模式,用到时才加载 =============================================*///    private static SingleMode instance ;//    private SingleMode(){}////    /**//     * 单例懒汉模式,用到时才加载//     * @return//     *///    public static SingleMode getInstance(){//        if (null==instance){//            instance = new SingleMode();//        }//        return instance;//    }    /**     * =============================== 单例饿汉模式,不等用到时就加载 =============================================     *///    private static SingleMode instance = new SingleMode();////    private SingleMode() {//    }////    public static SingleMode getInstance() {//        return instance;//    }    /**     * =============================== 多线程操作  注意线程安全 ============================================================     */    private static SingleMode instance;    private SingleMode() {    }    public static SingleMode getInstance() {        synchronized (instance) {            if (null == instance) {                instance = new SingleMode();            }        }        return instance;    }

0 0
原创粉丝点击