class="java">package com.supan; public interface Person { public void say(); } package com.supan; public class Chinese implements Person { public void say(){ System.out.println("I am chinese"); } } package com.supan; public class American implements Person { public void say() { System.out.println("I am American;"); } } package com.supan; public interface Animal { public void eat(); } package com.supan; public class Dog implements Animal { public void eat() { System.out.println("dog is eatting"); } } package com.supan; public class Cat implements Animal { public void eat() { // TODO Auto-generated method stub System.out.println("Cat is eattting"); } } //下面是重要的工厂类。 package com.supan; public class PersonFactory { public Object getObject(String name){ if(name.equals("Chinese")){ return new Chinese(); }else if(name.equals("American")){ return new American(); }else if(name.equals("dog")){ return new Dog(); }else if(name.equals("Cat")){ return new Cat(); } return null; } } //下面是测试类 package com.supan; public class FactoryTest { public static void main(String[] args) { PersonFactory pf = new PersonFactory(); American a = (American)pf.getObject("American"); a.say(); Chinese chinese = (Chinese)pf.getObject("Chinese"); chinese.say(); Dog dog = (Dog)pf.getObject("dog"); dog.eat(); Cat cat = (Cat)pf.getObject("Cat"); cat.eat(); } }