zoukankan      html  css  js  c++  java
  • 05 单例模式

    单例模式

    1、饿汉式

    public class HungerySingleton {
    
    	private HungerySingleton() {};
    	
    	private static HungerySingleton instance=new HungerySingleton();
    	
    	public static HungerySingleton getInstance() {
    		return instance;
    	}
    }
    

    在加载的时候已经被实例化,只有一次,线程安全

    但如果一直不使用,占用资源

    2、 懒汉式

    • 2.1 synchronized实现懒汉式

      由于使用了synchronized时代码退化为串行执行
        public class HoonSingleton {
    
    	private HoonSingleton() {};
    	
    	private static HoonSingleton instance;
    	
    	public synchronized static HoonSingleton getInstance() {
    		if (null==instance) {
    			instance=new HoonSingleton();
    		}
    		return instance;
    	}
    }
        
    
    • 2.2 使用DCL(double-checked-locking)实现懒汉式

    在构造方法中进行成员变量赋值时,如果代码进行了重排序,可能导致空指针异常

    public class DCLSingleton {
    
    	private DCLSingleton() {};
    	
    	private volatile static DCLSingleton instance=null;
    	
    	public static DCLSingleton getInstance() {
    		if (null==instance) {
    			synchronized (DCLSingleton.class) {
    				if (null==instance) {
    					instance=new DCLSingleton();
    				}
    			}
    		}
    		return instance;
    	}
    }
    
    • 2.3 使用内部类实现懒汉式

    public class HolderSingleton {
    	
    	private HolderSingleton() {};
    	
    	//原理:内部类在加载的时候不会初始化内部的变量,只有在用到的时候才会进行初始化,而且由jvm保证了线程安全
    	private static class Holder{
    		
    		private static HolderSingleton instance=new HolderSingleton();
    	}
    	
    	public static HolderSingleton getInstance() {
    		return Holder.instance;
    	}
    }
    
    • 2.4 使用枚举实现饿汉式

    public enum EnumSingleton {
    
    	//枚举有类加载后就直接初始化,相对于饿汉式
    	INSTANCE;
    	
    	public static EnumSingleton getInstance() {
    		return INSTANCE;
    	}
    }
    
    • 2.5 使用枚举内部类实现懒汉式

    public class EnumHolderSingleton {
    	
    	private EnumHolderSingleton() {}
    	
    	public static EnumHolderSingleton getInstance() {
    		return EnumHolder.instance;
    	}
    	
    	//依靠内部类延迟加载的功能实现懒汉式单例
    	private enum EnumHolder{
    		INSTANCE;
    		private static EnumHolderSingleton instance=new EnumHolderSingleton();
    	}
    }
    
  • 相关阅读:
    在多个游戏视图间切换环境准备
    精灵动画Animation对话框组成Idle动画的各精灵
    空函数有参函数调用参数的注意事项Swift 1.1语言
    使用NGUINGUI的相关介绍
    ARP侦查工具Netdiscover
    使用recon/domains-hosts/baidu_site模块,枚举baidu网站的子域
    Transform组件C#游戏开发快速入门
    为什么使用BeagleBoneBeagleBone的优点
    Java-JNA调用DLL(转)
    关于IP网段间互访的问题—路由是根本(转)
  • 原文地址:https://www.cnblogs.com/lifeone/p/11653140.html
Copyright © 2011-2022 走看看