@Override public void eat() { System.out.println("eat apple!"); } }
// Orange类实现了Fruit接口 class Orange implements Fruit{
@Override public void eat() { System.out.println("eat orange!"); } }
// 定义工厂类 class Factory{ public static Fruit getInstance(String className){ Fruit f = null; //定义接口对象 if("apple".equals(className)){ //判断是哪个类的标记 f = new Apple(); } if("orange".equals(className)){ //判断是哪个类的标记 f = new Orange(); } return f; } }
public class factory {
public static void main(String[] args) { Fruit f = null; //定义接口对象 f = Factory.getInstance("apple"); //通过工厂取得实例 f.eat(); //调用方法 }
@Override public void eat() { System.out.println("eat apple!"); } }
class Orange implements Fruit{
@Override public void eat() { System.out.println("eat orange!"); } }
// 定义工厂类 class Factory{ public static Fruit getInstance(String className){ Fruit f = null; //定义接口对象 try{ f = (Fruit)Class.forName(className).newInstance(); //实例化对象 }catch(Exception e){ e.printStackTrace(); } return f; } }
public class factory {
public static void main(String[] args) { Fruit f = null; //定义接口对象 f = Factory.getInstance("Apple"); //通过工厂取得实例 f.eat(); //调用方法 }