没有利用反射机制定义的简单工厂类
interface Fruit{ public void eat(); } class Apple implements Fruit{ public void eat(){ System.out.println("吃苹果"); } } class Orange implements Fruit{ public void eat(){ System.out.println("吃橘子"); } } //下面定义一个工厂,取得子类的实例化对象; class Factory{ public static Fruit getInstance(String className){ if("apple".equals(className)){ return new Apple(); }else if("orange".equals(className)){ return new Orange(); }else{ return null; } } } public class Test{ public static void main(String args[]){ Fruit f = Factory.getInstance("apple"); f.eat(); } }
时间: 2024-10-28 22:03:06