1.工厂接口
package test.my.maven.FactoryModel; public interface Person { void eat(); void water(); }
2. 工厂实现
package test.my.maven.FactoryModel; public class Boy implements Person { @Override public void eat() { System.out.println("Boy eat!!!"); } @Override public void water() { System.out.println("Boy water!!!"); } }
package test.my.maven.FactoryModel; public class Girl implements Person { @Override public void eat() { System.out.println("Girl eat!!!"); } @Override public void water() { System.out.println("Girl water!!!"); } }
3.工厂类实例获取
package test.my.maven.FactoryModel; public class PersonFactory { public static Object getInstance(Class<? extends Person> clazz){ try { return Class.forName(clazz.getName()).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } }
4.测试
package test.my.maven.FactoryModel; public class TestMain { public static void main(String[] args) { Person boy = (Person) PersonFactory.getInstance(Boy.class); if(null != boy) { boy.eat(); boy.water(); } Person girl = (Person) PersonFactory.getInstance(Girl.class); if(null != girl) { girl.eat(); girl.water(); } } }
5.结果
Boy eat!!!
Boy water!!!
Girl eat!!!
Girl water!!!