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
        }
        
    }

    这个单例线程安全

  • 相关阅读:
    jdk动态代理
    mysql-索引方案
    闭包的有点以及出现的内存泄露2016/4/12
    表单2016/4/8
    cursor
    同一个事件绑定不同的函数
    a:link visited hover active
    对于属性操作,加入属性,移除属性
    offset获取位置
    清除浮动6中方法
  • 原文地址:https://www.cnblogs.com/LUA123/p/7798596.html
Copyright © 2011-2022 走看看