JAVA单例模式

来源:互联网 发布:麟龙选股软件 编辑:程序博客网 时间:2024/05/18 01:41
/**
 * 单例模式-饿汉模式
 *
 * @author Austinson
 * 该类加载的时候会直接new一个对象出来,当这样的类比较多时就会使得启动的速度变慢,适合小系统。
 *
 */
public class SingletonByHungry {

    private static SingletonByHungry singletonByHungry = new SingletonByHungry();//初始化实例对象

    private SingletonByHungry() {//构建函数私有化,保证其他对象不能直接new一个此对象的实例
    };

    public static SingletonByHungry getSingletonByHungry() {
        return singletonByHungry;
    }

}

/**
 * 单例模式-懒汉模式
 *
 * @author Austinson
 *
 */
public class SingletonByLazy {

    // private static SingletonByLazy singletonByLazy = null;
    //
    // private SingletonByLazy() {
    // };
    //
    // /**
    // * 加synchronized关键字不会出现线程安全问题,但是会影响运行效率。
    // * @return
    // */
    // public static synchronized SingletonByLazy getSingletonByLazy() {
    // if (null == singletonByLazy) {
    // singletonByLazy = new SingletonByLazy();
    // }
    // return singletonByLazy;
    // }

    /** 双重校验 **/
    // 定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)
    private volatile static SingletonByLazy singletonByLazy = null;

    private SingletonByLazy() {
    };

    // 使用同步做二次校验,保证实例对象不被重复实例化,保证线程间的安全,也保证高效性
    public static SingletonByLazy getSingletonByLazy() {
        if (null == singletonByLazy) {
            // 二次校验
            synchronized (SingletonByLazy.class) {
                if (null == singletonByLazy) {
                    singletonByLazy = new SingletonByLazy();
                }
            }
        }
        return singletonByLazy;
    }

}





1 0
原创粉丝点击