zoukankan      html  css  js  c++  java
  • Singleton模式的五种实现

    单例模式的特点:

    • 单例类只能有一个实例。
    • 单例类必须自己创建自己的唯一实例。
    • 单例类必须给所有其他对象提供这一实例。 -《Java与模式》

    单例类可以是没有状态的,仅用做提供工具性函数的对象。既然是提供工具性函数,也就没有必要创建多个实例。

     

    下面列举单例模式的几种实现:

    • 单元素的枚举类型实现Singleton – the preferred approach.enum类型是Jdk1.5引入的一种新的数据类型.其背后的基本想法:通过公有的静态final域为每个枚举常量导出实例的类。因为没有可访问的构造器,枚举类型是真正的final。既不能创建枚举类型实例,也不能对它进行扩张 。枚举类型是实例受控的,是单例的泛型化,本质上是氮元素的枚举 -《Effective Java》P129
    public enum Singleton{
    	INSTANCE;
    	public void execute(){…}
    	public static void main(String[] agrs){
    		Singleton sole=Singleton.INSTANCE;
    		sole.execute();
    	}
    }
    
    • 懒汉式 – Lazy initialization . 构造函数是private,只有通过Singleton才能实例化这个类。
    public class Singleton{
    	private volatile static Singleton uniqueInstance=null;
    	private Singleton(){}
    	public static Singleton getInstance(){
    		if(uniqueInstance==null){
    			synchronized(Singleton.class){
    				if(uniqueInstance==null){
    					uniqueInstance=new Singleton();
    				}
    			}
    		}
    		return uniqueInstance;
    	}
    	//other useful methods here
    }
    • 饿汉式 – Eager initialization
    public class Singleton{
    	private static Singleton uniqueInstance=new Singleton();
    	private Singleton(){}
    	public static Singleton getInstance(){
    		return uniqueInstance;
    	}
    }
    • static block initialization
    public class Singleton{
    	private static final Singleton instance;
    		
    	static{
    		try{
    			instance=new Singleton();
    		}catch(IOException e){
    			thronw new RuntimeException("an error's occurred!");
    		}
    	}
    	public static Singleton getInstance(){
    		return instance;
    	}
    	private Singleton(){
    	}
    }
    • The solution of Bill Pugh 。- From wiki <Singleton Pattern> 。通过静态成员类来实现,线程安全。
    public class Singleton{
    	//private constructor prevent instantiation from other classes
    	private Singleton(){}
        
       	/**
        *SingletonHolder is loaded on the first execution of Singleton.getInstance()
        *or the first access to SingletonHolder.INSTANCE,not befor.
        */
         private static class SingletonHolder{
    		public static final Singleton instance=new Singleton();
    	 }
         private static Singleton getInstance(){
    		return SingletonHolder.instance;
    	 }
    }
  • 相关阅读:
    ntohs, ntohl, htons,htonl的比较和详解
    转 linux socket的select函数例子
    转 结构体中字节对齐问题(转载)
    C语言中volatile关键字的作用
    转 字符串模式匹配算法——BM、Horspool、Sunday、KMP、KR、AC算法
    转 常见hash算法的原理
    转 从头到尾彻底解析Hash表算法
    [CEOI2020 D2T1 / CF1403A] 权力药水The Potion of Great Power 题解
    [CEOI2020 D1T3 / CF1402C] 星际迷航Star Trek 题解
    [CEOI2020 D1T2 / CF1402B] 道路Roads 题解
  • 原文地址:https://www.cnblogs.com/matt123/p/2564393.html
Copyright © 2011-2022 走看看