zoukankan      html  css  js  c++  java
  • 五、单件模式

    经典单件

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

    线程安全的单件

    • 直接生成单件对象
    public class Singleton {
        private static Singleton uniqueInstance = new Singleton();
        private Singleton() {}
        public static Singleton getInstance() {
            return uniqueInstance;
        }
    }
    • 使用synchronized
    public class Singleton {
        private static Singleton uniqueInstance;
        private Singleton() {}
        public static synchronized Singleton getInstance() {
            if (uniqueInstance == null) {
                uniqueInstance = new Singleton();
            }
            return uniqueInstance;
        }
    }
    • 双重检查加锁
    public class Singleton {
        private volatile static Singleton uniqueInstance;
        private Singleton() {}
        public static Singleton getInstance() {
            if (uniqueInstance == null) {
                synchronized (Singleton.class) {
                    if (uniqueInstance == null) {
                        uniqueInstance = new Singleton();
                    }
                }
            }
            return uniqueInstance;
        }
    }

    个人理解

    单件模式确保一个类只有一个实例,并提供一个全局访问点。
    在经典的单件模式中,如果有两个线程访问一个单件模式,会发生线程安全的问题,产生两个单件实例。
    解决方法:
    1、在单件中直接生成单件对象,然后返回。(如果单件对象创建的开销比较大,会造成资源浪费)
    2、在单件的全局访问点上使用synchronized 关键字,可以解决问题。(线程同步会降低性能)
    3、使用双重检查加锁的方式,完美的解决问题。

  • 相关阅读:
    DS博客作业07--查找
    第五次作业——05图
    第四次作业——04树
    DS博客作业03--栈和队列
    DS博客作业02--线性表
    DS博客作业01--日期抽象数据类型设计与实现
    C语言博客05--指针
    C语言博客作业04--数组
    DS博客作业08--课程总结
    C语言-第0次作业
  • 原文地址:https://www.cnblogs.com/huacesun/p/6622496.html
Copyright © 2011-2022 走看看