public interface Fruit { public void eat(); }
public class Apple implements Fruit { @Override public void eat() { System.out.println("吃苹果"); } }
public class Orange implements Fruit { @Override public void eat() { System.out.println("吃橙子...."); } }
public class MyFactory { public static Fruit getInstance(String name) { if(name.equals("Apple")) { return new Apple(); }else if(name.equals("Orange")) { return new Orange(); }else { return null; } } }
public class Test { public static void main(String[] args) { /*Fruit f = new Orange(); f.eat();*/ Scanner input = new Scanner(System.in); System.out.println("请输入您要吃的水果名:"); String name = input.next(); Fruit f = MyFactory.getInstance(name); f.eat(); } }