zoukankan      html  css  js  c++  java
  • 设计模式-单例

    单例模式是一种常见的设计模式

    单例模式有以下特点:

      1、单例类只能有一个实例。
      2、单例类必须自己创建自己的唯一实例。
      3、单例类必须给所有其他对象提供这一实例。

    饿汉式单例

    public class Singleton {
    
        private static Singleton instance = new Singleton();
    
        public static Singleton getInstance() {
            return instance;
        }
    }

    在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变

    懒汉式单例

    public class Singleton {
    
        private static Singleton instance = null;
    
        /**
         * 懒汉模式一 
         * 同步方法
         */
        public static synchronized Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
    
            return instance;
        }
    
        /**
         * 懒汉模式二 
         * 同步代码块
         */
        public static Singleton getInstance() {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
    
            return instance;
        }
    }

    同步代码,或者同步代码块,效率低

    双重锁检查

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

    线程安全,提高效率

    内部静态类

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

    常见应用场景

    1. 计数器

    2. 共享日志

    3. Web应用配置对象

    4. 数据库连接池

    5. 多线程连接池

    好处

    资源共享的情况下,避免由于资源操作时导致的性能或损耗等。如日志文件,应用配置

    控制资源的情况下,方便资源之间的互相通信。如线程池

  • 相关阅读:
    hdu 2147 kiki's game
    HDU 1846 Brave Game
    NYOJ 239 月老的难题
    NYOJ 170 网络的可靠性
    NYOJ 120 校园网络
    xtu字符串 B. Power Strings
    xtu字符串 A. Babelfish
    图论trainning-part-1 D. Going in Cycle!!
    XTU 二分图和网络流 练习题 J. Drainage Ditches
    XTU 二分图和网络流 练习题 B. Uncle Tom's Inherited Land*
  • 原文地址:https://www.cnblogs.com/alex09/p/6649740.html
Copyright © 2011-2022 走看看