单例工厂
public abstract class Human { public abstract void doSomething(); } public class WhiteHuman extends Human { @Override public void doSomething() { } } public class YellowHuman extends Human { @Override public void doSomething() { } } public class Factory { private static final Map<String,Object> objectMap = new HashMap<String, Object>(); public synchronized static <T extends Human> T createHuman(Class<T> c){ Human human = null; String className = null; className =c.getName(); try { if (!objectMap.containsKey(className)) { Class class1 = Class.forName(className); Constructor constructor = class1.getDeclaredConstructor(); constructor.setAccessible(true); human = (Human) constructor.newInstance(); objectMap.put(className, human); } } catch (Exception e) { // TODO: handle exception } return (T)objectMap.get(className); } } //测试 public class Demo { public static void main(String[] s) { for(int i = 0; i < 100; i++){ System.out.println(Factory.createHuman(YellowHuman.class)); } } }