JAVA设计模式之单例模式

参考:http://blog.csdn.net/jason0539/article/details/23297037/    

http://www.blogjava.net/kenzhh/archive/2013/03/15/357824.html

/**
 * @author lishupeng
 * @Description
 * @Date 2017/12/9 11:16
 * <p>
 * 单例模式  :
 * <p>
 * 赖汉模式
 * <p>
 * 线程不安全
 */
public class Singleton {

    private Singleton() {
    }

    private static Singleton single = null;

    //静态工厂方法
    public static Singleton getInstance() {
        if (single == null) {
            single = new Singleton();
        }
        return single;
    }


    //在getInstance方法上加同步
    public static synchronized Singleton getInstance1() {
        if (single == null) {
            single = new Singleton();
        }
        return single;
    }

    //双重检查锁定
    public static Singleton getInstance2() {
        if (single == null) {
            synchronized (Singleton.class) {
                if (single == null) {
                    single = new Singleton();
                }
            }
        }
        return single;
    }

}
/**
 * @author lishupeng
 * @Description
 * @Date 2017/12/9 11:21
 *
 * 饿汉式单例类.在类初始化时,已经自行实例化
 *
 *
 * 饿汉式在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以天生是线程安全的。
 *
 */
public class Singleton1 {

    private Singleton1() {}
    private static final Singleton1 single = new Singleton1();


    //静态工厂方法
    public static Singleton1 getInstance() {
        return single;
    }

}
/**
 * @author lishupeng
 * @Description
 * @Date 2017/12/9 11:20
 *
 *
 * 静态内部类
 *
 * 既实现了线程安全,又避免了同步带来的性能影响。
 */
public class SingletonNew {


    private static class LazyHolder {
        private static final SingletonNew INSTANCE = new SingletonNew();
    }
    private SingletonNew (){}


    public static final SingletonNew getInstance() {
        return LazyHolder.INSTANCE;
    }


}

 

posted on 2017-12-09 11:29  ..小树苗  阅读(101)  评论(0编辑  收藏  举报

导航