zoukankan      html  css  js  c++  java
  • 单例模式:Java单例模式的几种写法及它们的优缺点

    总结下Java单例模式的几种写法:

    1. 饿汉式

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

    优点:实现简单,不存在多线程问题,直接声明一个私有对象,然后对外提供一个获取对象的方法。

    缺点:class 类在被加载的时候创建Singleton实例,如果对象创建后一直没有使用,则会浪费很大的内存空间,此方法不适合创建大对象。

    2. 懒汉式(线程不安全)

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

    优点:节省内存空间,在使用的时候才会创建;

    缺点:在多线程下,可能会创建多个实例(一定要重视这个问题,有时候如果在单例对象的构造方法中做了某些重要操作,创建多个实例可能会造成可怕后果,如:打开Android的Sqlite数据库连接)。

    3. 懒汉式(线程安全)

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

    优点:支持多线程,且以懒汉式的方式加载,不浪费内存空间。

    缺点:将 synchronized 块加在方法上,会影响并发量,每次调用getInstance()方法都会线程同步,效率十分低下。最重要的是,当创建好实例对象之后,就不必继续进行同步了。

    4.懒汉式(线程安全,推荐)

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

    优点:支持多线程,并发量高,且以懒汉式加载,不浪费内存空间。

    缺点:一时找不出缺点,非要说缺点的话,就是实现比较麻烦。

  • 相关阅读:
    poj 3669 Meteor Shower
    poj 3009 Curling 2.0
    poj 1979 Red and Black
    区间内素数的筛选
    九度oj 题目1347:孤岛连通工程
    poj 3723 Conscription
    poj 3255 Roadblocks
    Luogu P3975 [TJOI2015]弦论
    AT2165 Median Pyramid Hard 二分答案 脑洞题
    后缀自动机多图详解(代码实现)
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/11555891.html
Copyright © 2011-2022 走看看