zoukankan      html  css  js  c++  java
  • 单例模式中饿汉式和懒汉式

    单例模式属于创建型的设计模式,这个模式提供了创建对象的最佳方式。这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

    单例模式的两种实现方式

    1、饿汉式

    饿汉式就是类一旦加载,就把单例初始化完成,保证获取实例的时候,单例是已经存在的了。

    代码实现:

    /**
     * 饿汉式
     */
    public class SingletonHungry {
    
        private static SingletonHungry hungry = new SingletonHungry();
    
      //私有化构造方法,作用是不能自己创建该类的对象,只能通过下面的getInstance方法获取该类的实例
    private SingletonHungry(){ } public static SingletonHungry getInstance(){ return hungry; } }

    2、懒汉式

    懒汉式默认不会实例化,当调用getInstance时才会实例出来,不过懒汉式是线程不安全的

    代码实现:

    /**
     * 懒汉式,线程不安全
     */
    public class SingletonLazy {
    
        private static SingletonLazy lazy;
    
        private SingletonLazy(){
        }
    
        public static SingletonLazy getInstance(){
            if(lazy == null){
                lazy = new SingletonLazy();
            }
            return lazy;
        }
    }

    如果需要线程安全,可以加synchronized 锁,但是加锁会影响效率

    代码实现:

    /**
     * 懒汉式,线程安全
     */
    public class SingletonLazy {
    
        private static SingletonLazy lazy;
        private static String key = "key";
    
        private SingletonLazy(){
        }
    
        public static SingletonLazy getInstance(){
            if (lazy == null){
                synchronized (key) {
                    if(lazy == null){
                        lazy = new SingletonLazy();
                    }
                }
            }
            return lazy;
        }
    }
  • 相关阅读:
    Linux下几种文件传输命令 sz rz sftp scp
    jqGrid subGrid配置 如何首次加载动态展开所有的子表格
    MySQL使用规范
    Navicat连接MySQL报错2059
    微信小程序
    完美解决 ios10 及以上 Safari 无法禁止缩放的问题
    html5利用getObjectURL获取图片路径上传图片
    Vue的单页应用中如何引用单独的样式文件
    用JS添加和删除class类名
    APP中的 H5和原生页面如何分辨、何时使用
  • 原文地址:https://www.cnblogs.com/zhangcaihua/p/13158145.html
Copyright © 2011-2022 走看看