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

    懒汉式:

    package org.burning.sport.design.pattern.singlepattern;
    
    
    /**
     * 单例模式----懒汉式,在第一次调用的时候实例化自己
     *
     * (事实上,通过Java反射机制是能够实例化构造方法为private的类的,
     * 那基本上会使所有的Java单例实现失效。此问题在此处不做讨论,姑且掩耳盗铃地认为反射机制不存在。)
     */
    public class Singleton {
        //私有构造器,代表不能通过在外部new来创建对象
        private Singleton(){}
      //双重检查锁定的单例模式,这里必须加volatile
        private volatile static Singleton singleton = null;
        // 1.获取实例的静态工厂方法(线程不安全的)
        public static Singleton getInstance() {
            if(singleton == null) {
                singleton = new Singleton();
            }
    
            return singleton;
        }
    
        // 2.获取实例的静态工厂方法(线程安全的)
        public static synchronized Singleton getSafeInstance() {
            if(singleton == null) {
                singleton = new Singleton();
            }
            return singleton;
        }
    
        // 3.双重检查锁定
        public static Singleton getSafe2Instance() {
            if(singleton == null) {
                synchronized (Singleton.class) {
                    if(singleton == null) {
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }
    
        // 3. 这种获取实例的方式比1,2都好,既实现了线程安全,有避免了同步带来的性能影响
        public static final Singleton getSafe3Instance() {
            return LazyHolder.INSTANCE;
        }
    
        private static class LazyHolder {
            private static final Singleton INSTANCE = new Singleton();
        }
    }

    饿汉式:

    package org.burning.sport.design.pattern.singlepattern;
    
    /**
     * 单例模式----饿汉式单例
     *  饿汉式在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以天生是线程安全的。
     */
    public class Singleton2 {
        private Singleton2(){}
        private static final Singleton2 singleton = new Singleton2();
    
        public static Singleton2 getInstance() {
            return singleton;
        }
    }

     https://gitee.com/play-happy/base-project

  • 相关阅读:
    Linux权限
    Linux用户和用户组操作
    input输入框美化
    Ajax原理一篇就够了
    CSS样式----浮动(图文详解)
    linx系统操作
    文件打包,压缩,解包,解压缩
    Linux学习笔记(一)
    ios 11导航栏替换返回按钮图片,隐藏文字
    swift开发笔记23 BirthDays
  • 原文地址:https://www.cnblogs.com/happyflyingpig/p/7654354.html
Copyright © 2011-2022 走看看