zoukankan      html  css  js  c++  java
  • 创建模式之单例模式

    懒汉模式:

    /**
     * @author yuyang
     * @DATE 2019/1/7 0007-8:59
     */
    public class Singleton {
        private final static Singleton INSTANCE=null;
        private Singleton(){}
        public static synchronized Singleton getInstance(){
            if (INSTANCE==null){
                return  new Singleton();
            }else {
                return INSTANCE;
            }
        }
    }

    饿汉模式

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

    静态内部类

    public class Singleton {
        private Singleton() {}
        private static class SingletonInstance {
            private static final Singleton INSTANCE = new Singleton();
        }
        public static Singleton getInstance() {
            return SingletonInstance.INSTANCE;
        }
    }
    同步方法

    同步代码块

    双重检查

    public class Singleton {
        private static volatile Singleton singleton;
        private Singleton() {}
        public static Singleton getInstance() {
            if (singleton == null) {
                synchronized (Singleton.class) {
                    if (singleton == null) {
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }
    }
  • 相关阅读:
    Samba 基础搭建
    HBuilder 打包流程和遇到的坑
    js 字符串查找相同字母最长子串
    web前端简单的H5本地存储
    rem响应式JS
    JS洗牌算法
    Js 常用正则表达式
    JS_DOM_鼠标、键盘事件合集
    SE 2014年4月3日
    SE 2014年4月2日
  • 原文地址:https://www.cnblogs.com/yuyangcoder/p/10231383.html
Copyright © 2011-2022 走看看