Hutool之单例池——Singleton

为何会有这个类

日常咱们使用单例不外乎两种方式:安全

  1. 在对象里加个静态方法getInstance()来获取。此方式能够参考 【转】线程安全的单例模式 这篇博客,可分为饿汉和饱汉模式。
  2. 经过Spring这类容器统一管理对象,用的时候去对象池中拿。Spring也能够经过配置决定懒汉或者饿汉模式

说实话我更倾向于第二种,可是Spring更对的的注入,而不是拿,因而我想作Singleton这个类,维护一个单例的池,用这个单例对象的时候直接来拿就能够,这里我用的懒汉模式。我只是想把单例的管理方式换一种思路,我但愿管理单例的是一个容器工具,而不是一个大大的框架,这样能大大减小单例使用的复杂性。框架

使用

package com.xiaoleilu.hutool.demo;

import com.xiaoleilu.hutool.Singleton;

/**
 * 单例样例
 * @author loolly
 *
 */
public class SingletonDemo {
	
	/**
	 * 动物接口
	 * @author loolly
	 *
	 */
	public static interface Animal{
		public void say();
	}
	
	/**
	 * 狗实现
	 * @author loolly
	 *
	 */
	public static class Dog implements Animal{
		@Override
		public void say() {
			System.out.println("汪汪");
		}
	}
	
	/**
	 * 猫实现
	 * @author loolly
	 *
	 */
	public static class Cat implements Animal{
		@Override
		public void say() {
			System.out.println("喵喵");
		}
	}
	
	public static void main(String[] args) {
		Animal dog = Singleton.get(Dog.class);
		Animal cat = Singleton.get(Cat.class);
		
		//单例对象每次取出为同一个对象,除非调用Singleton.destroy()或者remove方法
		System.out.println(dog == Singleton.get(Dog.class));		//True
		System.out.println(cat == Singleton.get(Cat.class));			//True
		
		dog.say();		//汪汪
		cat.say();		//喵喵
	}
}

总结

你们若是有兴趣能够看下这个类,实现很是简单,一个HashMap用于作为单例对象池,经过newInstance()实例化对象(不支持带参数的构造方法),不管取仍是建立对象都是线程安全的(在单例对象数量很是庞大且单例对象实例化很是耗时时可能会出现瓶颈),考虑到在get的时候使双重检查锁,可是并非线程安全的,故直接加了synchronized作为修饰符,欢迎在此给出建议。ide

相关文章
相关标签/搜索