1 /**
2 * @author Moriatry 设计模式之 工厂模式
3 */
4
5 interface fruit{
6 public abstract void eat();
7 }
8
9 class Apple implements fruit{
10 public void eat(){
11 System.out.println("Apple");
12 }
13 }
14
15 class Orange implements fruit{
16 public void eat(){
17 System.out.println("Orange");
18 }
19 }
20
21 // 构造工厂类
22 // 也就是说以后如果我们在添加其他的实例的时候只需要修改工厂类就行了
23 class Factory{
24 public static fruit getInstance(String fruitName){
25 fruit f=null;
26 if("Apple".equals(fruitName)){
27 f=new Apple();
28 }
29 if("Orange".equals(fruitName)){
30 f=new Orange();
31 }
32 return f;
33 }
34 }
35 class hello{
36 public static void main(String[] a){
37 fruit f=Factory.getInstance("Orange");
38 f.eat();
39 }
40
41 }