• 单例模式中饿汉式和懒汉式


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

    单例模式的两种实现方式

    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;
        }
    }
  • 相关阅读:
    一个asp.net MVC 的分页代码
    JavaScript教程:JavaScript如何判定用户浏览器类型和版本号?
    CutyCapt A Qt WebKit Web Page Rendering Capture Utility
    Top 10 Algorithms in Data Mining
    a c++ bloger
    设置MYSQL允许用IP访问
    QtWebKit Module
    kubuntudesktop nearly 700m,so big
    Wt, C++ Web Toolkit Introduction
    硅谷、纽约、伦敦如何演绎世界三大科技中心
  • 原文地址:https://www.cnblogs.com/zhangcaihua/p/13158145.html
Copyright © 2020-2023  润新知