zoukankan      html  css  js  c++  java
  • 单例模式的几种写法

    一、懒汉式

    public class Singleton {
    
        // 私有的构造函数
        private Singleton() {
            
        }
        
        // 静态变量
        private static Singleton instance;
        
        // 静态方法
        public static Singleton getInstance() {
            // 当instance为null时赋值
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }

    二、饿汉式

    public class Singleton {
    
        // 私有的无参构造函数
        private Singleton() {
            
        }
        
        // 静态变量
        private static Singleton instance = new Singleton();
        
        // 静态方法
        public static Singleton getInstance() {
            return instance;
        }
    }

    三、占位符式

    public class Singleton {
    
        // 私有的构造方法
        private Singleton() {
            
        }
        
        // 静态内部类
        private static class SingletonInstance {
            private static Singleton instance = new Singleton();
        }
        
        // 静态方法
        public static Singleton getInstance() {
            return SingletonInstance.instance;
        }
    
    }
  • 相关阅读:
    springMVC静态资源
    MyBatis Generator
    使用springMVC时的web.xml配置文件
    Semaphore
    spring注解驱动--组件注册
    第1章 初始Docker容器
    docker面试整理
    第5章 运输层
    验证码
    带进度条的上传
  • 原文地址:https://www.cnblogs.com/libra0920/p/6140285.html
Copyright © 2011-2022 走看看