zoukankan      html  css  js  c++  java
  • 剑指offer第二版-2.实现单例模式

    面试题2:实现单例模式

    题目要求:
    设计一个类,只能生成该类的一个实例。

    /**
     * 单例模式
     * 定义:指实现了特殊模式的类,该类仅能被实例化一次,产生唯一的一个对象
     * 应用举例:windows的任务管理器,回收站,web应用的配置对象,spring中的bean默认也是单例
     * 分类:饿汉式,懒汉式,双检锁,静态内部类,枚举
     * 评价指标有:单例(必须),线程安全,延迟加载,防止反序列化产生新对象,防止反射攻击
     * 实现方法的选择:一般情况下直接使用饿汉式就好了,要求延迟加载时倾向于用静态内部类,涉及到反序列化创建对象或反射问题最好选择枚举
     * 
     * @since 2019年1月24日 下午2:35:36
     * @author xuchao
     *
     */
    public class P2_Singleton {
    
        public static void main(String[] args) {
            // 调用方式
            Singleton1 singleton1 = Singleton1.getInstance();
            Singleton2 singleton2 = Singleton2.getInstance();
            Singleton3 singleton3 = Singleton3.getInstance();
            Singleton4 singleton4 = Singleton4.getInstance();
        }
    }
    
    // 版本一:饿汉式
    // 特点:线程安全;在类初始化执行到静态属性时就分配了资源,有资源浪费问题;
    class Singleton1 {
        // 1.将构造方法私有化,不允许外部直接创建对象
        private Singleton1() {
        }
        // 2.创建类的唯一实例,使用private static修饰
        private static Singleton1 instance = new Singleton1();
    
        // 3.提供一个用于获取实例的方法,使用public static修饰
        public static Singleton1 getInstance() {
            return instance;
        }
    }
    
    // 版本二:懒汉式(非线程安全)
    // 特点:在第一次调用获取实例方法时分配内存,实现了懒加载;非线程安全;
    class Singleton2 {
        private Singleton2() {
        }
    
        private static Singleton2 instance;
    
        public static Singleton2 getInstance() {
            if (instance == null) {
                instance = new Singleton2();
            }
            return instance;
        }
    }
    
    // 版本三:懒汉式变种(synchronized同步方法,支持多线程)
    // 特点:线程安全;synchronized而造成的阻塞致使效率低,而且很多的阻塞都是没必要的。
    class Singleton3 {
        private Singleton3() {
        }
    
        private static Singleton3 instance;
    
        public static synchronized Singleton3 getInstance() {
            if (instance == null) {
                instance = new Singleton3();
            }
            return instance;
        }
    }
    
    // 版本四:懒汉式变种(synchronized同步块,支持多线程)
    // 特点:写法不同,但与版本三有一样的问题
    class Singleton4 {
        private Singleton4() {
        }
    
        private static Singleton4 instance;
    
        public static Singleton4 getInstance() {
    
            synchronized (Singleton4.class) {
                if (instance == null) {
                    instance = new Singleton4();
                }
            }
            return instance;
        }
    }
  • 相关阅读:
    动态封杀与解封IP
    潜谈IT从业人员在传统IT和互联网之间的择业问题(下)-互联网公司
    潜谈IT从业人员在传统IT和互联网之间的择业问题(上)-传统乙方形公司
    博主2000年真实遇鬼记-仅作记录以供后人参考
    异步请求引发的Chrome死锁
    jboss规则引擎KIE Drools 6.3.0 Final 教程(3)
    jboss规则引擎KIE Drools 6.3.0 Final 教程(2)
    jboss规则引擎KIE Drools 6.3.0 Final 教程(1)
    商品搜索引擎---推荐系统设计
    大道理很多人都懂,只是坚持不下去(浅谈坚持)
  • 原文地址:https://www.cnblogs.com/chao-zjj/p/10334373.html
Copyright © 2011-2022 走看看