zoukankan      html  css  js  c++  java
  • Offer_2:实现Singleton模式

    题目

    设计一个类,我们只能生成该类的一个实例。

    解题分析

    单例模式的特点:

    • 由于要求只能生成一个实例,因此必须私有化构造函数,以禁止手动 new 创建实例
    • 单例模式要求提供统一入口获取唯一实例
    • 单例模式必须保证多线程下的安全性

    代码

    单例模式的代码有好几种写法,这里只提供几种最优方法。。。

    利用静态内部类实现按需创建实例

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

    加锁前后两次判断实例是否已经存在

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

    利用枚举实现单例

    public enum Singleton {
        INSTANCE;
    
        public Singleton getInstance() {
            return INSTANCE;
        }
    }
    
  • 相关阅读:
    安卓第三次作业
    安卓第二次作业
    十三周作业
    2020年5月28日
    十二周上机练习
    十一周作业
    2020年5月14日
    2020年5月7日上机练习
    第九周练习
    Online Tristesse
  • 原文地址:https://www.cnblogs.com/dtdx/p/13709287.html
Copyright © 2011-2022 走看看