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. 多线程连接池

    好处

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

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

  • 相关阅读:
    oracle常用的sql语句
    Tomcat内存调优
    基于Linux服务器的Oracle自动备份以及定时清除
    Windows 中Oracle数据库定时备份与清除
    CentOS 7 root密码修改
    weblogic忘记用户密码
    weblogic修改密码
    通过python自动获取小说并下载
    Linux修改本机名称
    CentOS无法正常启动
  • 原文地址:https://www.cnblogs.com/alex09/p/6649740.html
Copyright © 2011-2022 走看看