工厂模式简单例子

工厂模式:

 1 package factorymode;
 2 /**
 3  * 工厂模式简单例子
 4  * @author Administrator
 5  *
 6  */
 7 public class FactoryDemo {
 8 
 9     public static void main(String[] args) {
10         IFruit fruit = Factory.getFrit("橘子");
11         if(fruit != null) {
12             System.out.println(fruit.get());
13         } else {
14             System.out.println("不存在");
15         }
16     }
17 
18 }
19 
20 interface IFruit {
21     public String get();
22 }
23 
24 class Factory {
25     public static IFruit getFrit(String name) {
26         //根据调用者传进来的描述,返回调用者所需要的对象实例
27         if(name.equals("苹果")) {
28             return new Apple();
29         } else if (name.equals("橘子")) {
30             return new Orange();
31         } else {
32             return null;
33         }
34     }
35 }
36 
37 class Apple implements IFruit {
38     public String get() {
39         return "采摘苹果";
40     }
41 }
42 
43 class Orange implements IFruit {
44     public String get() {
45         return "采摘橘子";
46     }
47 }
原文地址:https://www.cnblogs.com/enjoyjava/p/8192239.html