继续以女娲造人为例吧。
图二去掉了图一中的抽象类,同时把createHuman方法设置为静态类型,简化了类的创建过程,变更的源码仅仅是HumanFactory和NvWa类
package FactoryP; public class HumanFoctory1 { public static <T extends Human> T createHuman(Class<T> c){ Human human = null; try { human = (Human) Class.forName(c.getName()).newInstance(); }catch (Exception e){ System.out.println(e); } return (T) human; } }
package FactoryP; public class NvWa1 { public static void main(String[] args){ System.out.println("--------简单工厂第一批----------"); Human whiteHuan = HumanFoctory1.createHuman(WhiteHuman.class); whiteHuan.talk(); whiteHuan.color(); } }