java 工廠模式 例項
阿新 • • 發佈:2019-02-02
package 工廠模式; public class FruitFactory { public static void main(String[] args) { Fruit apple=Factory.getInstance("apple"); apple.eat(); Fruit li=Factory.getInstance("Li"); li.eat(); } } interface Fruit { public void eat(); } class Apple implements Fruit { @Override public void eat() { System.out.println("吃蘋果!"); } } class Li 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 Li(); } return f; } }