利用简单工厂设计模式参考以下给定的代码设计一个测试程序。 interface Fruit 定义一个水果的接口 public void eat ; 吃水果的方法 class Apple implements Fruit 定义子类 —— Apple public void eat ……………… class Orange implements Fruit 定义子类 —— Orange pub
public class Test { public static void main(String[] args) { Fruit apple = Factory.getInstance("apple"); apple.eat(); // 输出:吃苹果
Fruit orange = Factory.getInstance("orange");
orange.eat(); // 输出:吃橘子
}
}
interface Fruit { void eat(); }
class Apple implements Fruit { @Override public void eat() { System.out.println("吃苹果"); } }
class Orange implements Fruit { @Override public void eat() { System.out.println("吃橘子"); } }
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; } }
原文地址: http://www.cveoy.top/t/topic/bs8R 著作权归作者所有。请勿转载和采集!