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;
        private Singleton() {};
        public static synchronized Singleton getInstance() {
            if(uniqueInstance == null) {
                uniqueInstance = new Singleton();
            }
            return uniqueInstance;
        }
    }

    二、改良版,效率高。

    public class Singleton {
        
        private volatile static Singleton uniqueInstance; // volatile关键字确保多线程正确处理 uniqueInstance
        private Singleton() {};
        
        public static Singleton getInstance() {
            if(uniqueInstance == null) {
                synchronized(Singleton.class) {
                    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;
        }
    }

    以上就是单件模式(单例模式),是很简单吧

  • 相关阅读:
    最简单跳转,待反混爻的合集
    搜索引擎劫持代码
    Warning: Cannot modify header information
    editplus 正则删换行
    在全程Linux環境部署IBM Lotus Domino/Notes 8.5
    3.5-杂项②
    3.4-杂项①
    3.3-ISDN
    3.2-帧中继②
    3.2-帧中继①
  • 原文地址:https://www.cnblogs.com/M-Anonymous/p/13197695.html
Copyright © 2011-2022 走看看