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

    这个单例线程安全

  • 相关阅读:
    python_ 学习笔记(hello world)
    python_ 学习笔记(运算符)
    MySQL-联合查询
    MySQL-date和datetime
    python_ 学习笔记(基本数据类型)
    python_ 学习笔记(基础语法)
    Visaul Studio 常用快捷键的动画演示
    IIS日志-网站运维的好帮手
    浅谈反射机制
    SQL Server 数据库优化文章
  • 原文地址:https://www.cnblogs.com/LUA123/p/7798596.html
Copyright © 2011-2022 走看看