• 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;
        }
    
    
    }
  • 相关阅读:
    精简菜单和完整菜单之间进行切换
    QBC运算符含义
    STL源代码剖析——STL算法stl_algo.h
    TI_DSP_corePac_带宽管理
    scrapy-redis源代码分析
    SVG 贝塞尔曲线控制【方便设置】:贝塞尔曲线
    Zoj 2100 Seeding
    快慢指针和链表原地反转
    Gradle 编译多个project(包括多Library库project依赖)指导
    供应商地点信息更新
  • 原文地址:https://www.cnblogs.com/lishupeng/p/8010969.html
Copyright © 2020-2023  润新知