利用接口实现简单工厂模式

 1 package com.wisezone.factory;
 2 
 3 /**
 4  * 使用接口实现一个水果工厂
 5  * @author 王东海
 6  * @2017年4月16日
 7  */
 8 public interface Fruit
 9 {
10     void eat();
11 }
 1 package com.wisezone.factory;
 2 
 3 /**
 4  * 苹果
 5  * @author 王东海
 6  * @2017年4月16日
 7  */
 8 public class Apple implements Fruit
 9 {
10 
11     @Override
12     public void eat()
13     {
14         System.out.println("夏天吃苹果。。。");
15     }
16 
17 }
 1 package com.wisezone.factory;
 2 
 3 /**
 4  * 梨
 5  * @author 王东海
 6  * @2017年4月16日
 7  */
 8 public class Pear implements Fruit
 9 {
10 
11     @Override
12     public void eat()
13     {
14         System.out.println("夏天吃梨。。。");
15         
16     }
17 
18 }
 1 package com.wisezone.factory;
 2 
 3 /**
 4  * 简单工厂模式----利用接口----实现水果工厂
 5  * @author 王东海
 6  * @2017年4月16日
 7  */
 8 public class FactoryInterface
 9 {
10     public static Fruit product(String type){
11         if ("apple".equalsIgnoreCase(type))
12         {
13             return new Apple();
14         }else if ("pear".equalsIgnoreCase(type))
15         {
16             return new Pear();
17         }
18         return null;
19     }
20     
21     public static void main(String[] args)
22     {
23         Fruit fruit = FactoryInterface.product("apple");
24         fruit.eat();
25     }
26 }

结果为:夏天吃苹果。。。

posted @ 2017-04-16 16:46  程序员的世界。。。  阅读(171)  评论(0编辑  收藏  举报