這個對於性能來講,是沒有任何做用的,但對於mvc的實現缺有着很是重要的做用。java
package com.wolf.action; import java.util.HashMap; import java.util.Map; public class demo { public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println(Son.getInstance().getName()); System.out.println("我是誰"); } } class Son extends Father { private String name = "兒子"; final String CLASS = "demo"; protected String getName() { return this.query("aaa"); } public static Son getInstance() throws InstantiationException, IllegalAccessException, ClassNotFoundException { // 這裏必須是全局路徑 不然沒法找到 return (Son) instance("com.wolf.action.Son"); } } class Father { private static Map<String, Object> instance = new HashMap<String, Object>(); private String name = "父類"; protected void Fatcher() { System.out.println("我是父類"); } protected String query(String sql) { return sql + "has been done"; } public static Object instance(String objname) throws InstantiationException, IllegalAccessException, ClassNotFoundException { if (instance.get(objname) == null || !(instance.get(objname) instanceof Father)) { instance.put(objname, Class.forName(objname).newInstance()); } return instance.get(objname); } }