第一步: 新建接口,内含eat() 方法
People.java
package com.xuzhiwen.spring2; public interface People { public abstract void eat(); }
第二步:编写两个实现类
Man.java
package com.xuzhiwen.spring2; public class Man implements People{ @Override public void eat() { System.out.println("man est()..."); } }
Woman.java
package com.xuzhiwen.spring2; public class Woman implements People{ @Override public void eat() { System.out.println("Woman est()..."); } }
第三步:编写工厂类
PeopleFactory.java
package com.xuzhiwen.spring2; public class PeopleFactory { public static People getInstance(String className){ People p = null; try { p = (People) Class.forName(className).newInstance(); } catch (Exception e) { e.printStackTrace(); } return p; } }
第四步:编写测试类
package com.xuzhiwen.spring2; public class TestPeople { public static void main(String[] args) { People p = PeopleFactory.getInstance("com.xuzhiwen.spring2.Woman"); p.eat(); } }
第五步:运行结果如下