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

    饿汉单例模式:

    package com.design.singleton;
    
    public class EagerSingleton {
    
        private static final EagerSingleton EAGER_SINGLETON = new EagerSingleton();
    
        private EagerSingleton(){}
    
        public static EagerSingleton getInstance(){
            return EAGER_SINGLETON;
        }
    }

    当这个类被加载时,静态变量 EAGER_SINGLETON 就会被初始化。

     懒汉式单例:

    package com.design.singleton;
    
    public class LazySingleton {
    
        private static LazySingleton lazySingleton = null;
    
        private LazySingleton(){}
    
        public synchronized static LazySingleton getInstance(){
            if (lazySingleton == null){
                return new LazySingleton();
            }
            return lazySingleton;
        }
    
    }

    【区别】饿汉单例模式在自己被加载时就将自己实例化。从资源利用的角度讲,饿汉比懒汉差点。从速度和反应时间来讲,饿汉比懒汉块。懒汉在实例化的时候,需要处理多线程的问题。

    还有一种用的比较多的

    静态内部类单例:

    package com.design.singleton;
    
    public class InnerSingleton {
    
        private InnerSingleton(){}
    
        private static class Inner{
            private static InnerSingleton Instance = new InnerSingleton();
        }
    
        public static InnerSingleton getInstance(){
            return Inner.Instance;
        }
        
        public void doSomething(){
            // do something
        }
        
    }

    这个单例线程安全

  • 相关阅读:
    BFS(广搜训练题目)
    练习赛1(补题)
    练习赛1(AC题)
    codeup 1743: 算法3-4:表达式求值
    数学相关(更新ing)
    c语言常用函数(更新ing)
    大牛的博客(学习不止,更新不止)
    51nod 1005 大数加法
    js1-----预览js内容
    css10---转载---定位,浮动
  • 原文地址:https://www.cnblogs.com/LUA123/p/7798596.html
Copyright © 2011-2022 走看看