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

    静态内部类实现

    package com.haxianhe.singleton;
    
    /**
     * 静态内部类
     */
    public class Singleton5 {
        private Singleton5() {
    
        }
    
        private static class InstanceFactory {
            public static Singleton5 instance = new Singleton5();
        }
    
        public static Singleton5 getInstance() {
            return InstanceFactory.instance;
        }
    }
    

    饿汉模式

    package com.haxianhe.singleton;
    /**
     * 饿汉模式
     * */
    public class Singleton4 {
        private Singleton4() {
    
        }
    
        private static Singleton4 instance = new Singleton4();
    
        public static Singleton4 getInstance() {
            return instance;
        }
    }
    

    懒汉模式(双重锁检测)

    package com.haxianhe.singleton;
    
    /**
     * 双重锁检测(懒汉模式)
     */
    public class Singleton3 {
        /* 私有构造方法,防止被实例化 */
        private Singleton3() {
    
        }
    
        /* 私有实例变量,防止被引用 */
        private static Singleton3 instance = null;
    
        public static Singleton3 getInstance() {
            if (instance == null) {
                synchronized (instance) {
                    if (instance == null) {
                        instance = new Singleton3();
                    }
                }
            }
            return instance;
        }
    }
    
  • 相关阅读:
    求解:块级元素的宽度自适应问题
    list 小练习
    codevs1017乘积最大
    codevs1048石子归并
    luogu1387 最大正方形
    BZOJ1305: [CQOI2009]dance跳舞
    linux下分卷tar.bz文件的合并并解压缩
    ubuntu命令查补
    认识与学习BASH(中)
    认识与学习BASH
  • 原文地址:https://www.cnblogs.com/haxianhe/p/9271014.html
Copyright © 2011-2022 走看看