Java设计模式泛型化之单例模式

单例模式有多个形式。这里就拣其中一种来说说吧。

未泛型化的单例模式:

public class Singleton {
	
	private static final Singleton instance = new Singleton();
	
	private Singleton() {}
	
	public synchronized static Singleton getInstance() {
		return instance;
	}
	
	public void doSomething() {
		// TODO your code here.
	}
}

调用者:

public class SingletonCaller {

	public static void main(String[] args) throws Exception {
		Singleton s = Singleton.getInstance();
		s.doOtherthing();
	}
}

泛型化后的单例模式:

亲,泛型化是抽象设计哦。那意思是咱这个泛型化的单例模式可以处理你自定义的类的单例化。

你自定义的准备单例化的类

public class MySingleton extends Singleton {

	public void doOtherthing() {
		System.out.println("My singleton do otherthing.");
	}
}

泛型化的单例

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
public class Singleton {
	
	private static Map, Singleton> INSTANCES_MAP = 
			new HashMap, Singleton>();

	protected Singleton() {}
	
	public synchronized static  Singleton getInstance(Class instanceClass) throws Exception {
		if (INSTANCES_MAP.containsKey(instanceClass)) {
			return (E) INSTANCES_MAP.get(instanceClass);
		} else {
			E instance = instanceClass.newInstance();
			INSTANCES_MAP.put(instanceClass, instance);
			return instance;
		}
	}
	
}

调用者

public class SingletonCaller {

	public static void main(String[] args) throws Exception {
		MySingleton s = (MySingleton) Singleton.getInstance(MySingleton.class);
		s.doOtherthing();
	}
}

就是这样。

你可能感兴趣的:(设计,Java,Java技术)