• JAVA设计模式-单例模式


    方式一:适合单线程模式(不推荐)

    public class Singleton {
        private static Singleton sg = new Singleton();;
    
        private Singleton() {
        }
    
        public static Singleton getInstance() {
            if (sg == null) {
                sg = new Singleton();
            }
            return sg;
        }
    }

    方式二:没有延迟加载(不推荐)

    public class Singleton {
        private static Singleton sg = new Singleton();;
    
        private Singleton() {
        }
    
        public static Singleton getInstance() {
            return sg;
        }
    }

    方式三:不适合高并发(不推荐)

    public class Singleton {
        private static Singleton sg = new Singleton();;
    
        private Singleton() {
        }
    
        public static synchronized Singleton getInstance() {
            if (sg == null) {
                sg = new Singleton();
            }
            return sg;
        }
    }

    方式四:双重检测(推荐)

    public class Singleton {
        private static Singleton sg;
    
        private Singleton() {
        }
    
        public static Singleton getInstance() {
            if (sg == null) {
                synchronized (Singleton.class) {
                    if (sg == null) { // 双检索避免重复创建单例
                        sg = new Singleton();
                    }
                }
            }
            return sg;
        }
    }

    方式五:推荐

    public class Singleton {
        private Singleton() {
        }
    
        private static class SingletonHolder {
            private final static Singleton sg = new Singleton();
        }
    
        public static Singleton getInstance() {
            return SingletonHolder.sg;
        }
    }

    学了Java多年,一直都是用方式一、方式二和方式三,今天才发现方式四,百度后才知道方式五。

  • 相关阅读:
    Microsoft EBooks
    JavaScript 数据访问(通译自High Performance Javascript 第二章) [转]
    time random sys os模块
    configparser logging collections 模块
    序列化模块和hashlib模块
    内置方法
    面向对象进阶
    property classmethod staticmethod的用法
    归一化设计,抽象类和接口类,接口隔离操作
    面向对象的三大属性
  • 原文地址:https://www.cnblogs.com/zhi-leaf/p/10507173.html
Copyright © 2020-2023  润新知