• 设计模式 单例模式


    继续设计模式,这个模式用得应该很频繁啊,而且也比较简单,如果现在你还不能纸笔随手写个单例出来,你就得加油了哈~

    直接介绍几种线程安全的且我觉得还比较不错的方式:

    1、是不是号称恶汉,就是类加载就初始化了

    package com.zhy.pattern.singlton;
    
    public class Singleton
    {
    	private static Singleton instance = new Singleton();
    	
    	public static Singleton getInstance()
    	{
    		return instance ;
    	}
    }
    2、懒汉,我喜欢这种,需要双重判断

    package com.zhy.pattern.singlton;
    
    
    public class Singleton02
    {
    	private static Singleton02 instance;
    
    	public static Singleton02 getInstance()
    	{
    		if (instance == null)
    		{
    			synchronized (Singleton02.class)
    			{
    				if (instance == null)
    				{
    					instance = new Singleton02();
    				}
    			}
    		}
    		return instance;
    	}
    }

    3、使用Java的枚举,还是很推荐的,简单的跟神马一样,如果对枚举不熟悉,小google一下

    public enum Singleton03
    {
    	INSTANCE;
    }
    

    4、使用一个持有类,主要是为了不在初始化的时候加载

    package com.zhy.pattern.singlton;
    
    public class Singleton04
    {
    	private static final class InstanceHolder
    	{
    		private static Singleton04 INSTANCE = new Singleton04();
    	}
    
    	public static Singleton04 getInstance()
    	{
    		return InstanceHolder.INSTANCE;
    	}
    }
    

    好了,就这么多,以上4种都是比较推荐使用的,除了第一种会类加载的时候初始化,其他3中都不会,且4种都保证线程安全,特殊情况(除了多个类加载器,和你非要通过反射等手段生成多个对象)不考虑。


  • 相关阅读:
    在eclipse外边打开浏览器
    双开Eclipse
    6.5版本的CentOSLinux
    Intel x86_64 Architecture Background 3
    Java 大数、高精度模板
    Intel x86_64 Architecture Background 2
    Intel x86_64 Architecture Background 1
    Codeforces 999D Equalize the Remainders (set使用)
    Codeforces 996E Leaving the Bar (随机化)
    欧拉函数(小于或等于n的数中与n互质的数的数目)&& 欧拉函数线性筛法
  • 原文地址:https://www.cnblogs.com/oversea201405/p/3752014.html
Copyright © 2020-2023  润新知