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

    方式一:适合单线程模式(不推荐)

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

    方式二:没有延迟加载(不推荐)

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

    方式三:不适合高并发(不推荐)

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

    方式四:双重检测(推荐)

    public class Singleton {
        private static Singleton sg;
    
        private Singleton() {
        }
    
        public static Singleton getInstance() {
            if (sg == null) {
                synchronized (Singleton.class) {
                    if (sg == null) { // 双检索避免重复创建单例
                        sg = new Singleton();
                    }
                }
            }
            return sg;
        }
    }

    方式五:推荐

    public class Singleton {
        private Singleton() {
        }
    
        private static class SingletonHolder {
            private final static Singleton sg = new Singleton();
        }
    
        public static Singleton getInstance() {
            return SingletonHolder.sg;
        }
    }

    学了Java多年,一直都是用方式一、方式二和方式三,今天才发现方式四,百度后才知道方式五。

  • 相关阅读:
    MySQL 通过多个示例学习索引
    git reset的用法
    git rebase的用法
    学习yii2.0——依赖注入
    学习yii2.0——行为
    学习yii2.0——事件
    学习yii2.0——数据验证
    让Apache和Nginx支持php-fpm模块
    安装python3
    使用php操作memcache
  • 原文地址:https://www.cnblogs.com/zhi-leaf/p/10507173.html
Copyright © 2011-2022 走看看