一、先演示 “简单工厂”:
1 package org; 2 3 interface Fruit { 4 public void eat(); 5 } 6 7 class Apple implements Fruit { 8 public void eat() { 9 System.out.println("吃苹果。"); 10 } 11 } 12 13 class Orange implements Fruit { 14 public void eat() { 15 System.out.println("吃橘子"); 16 } 17 } 18 19 class Factory { // 工厂类 20 public static Fruit getInstance(String className) { 21 Fruit f = null; 22 if (className.equals("apple")) { 23 f = new Apple(); 24 } 25 if (className.endsWith("orange")) { 26 f = new Orange(); 27 } 28 return f; 29 } 30 } 31 32 public class FactoryDemo { 33 public static void main(String args[]) { 34 Fruit f = Factory.getInstance("apple"); 35 f.eat(); 36 } 37 }