代码改变世界

简单工厂模式

2010-08-26 22:21  Clingingboy  阅读(371)  评论(0编辑  收藏  举报


一个静态类工厂

先定义具体接口和类

interface IProduct {
   string ShipFrom();
 }
 
 class ProductA : IProduct {
   public String ShipFrom () {
     return " from South Africa";
   }
 }
 
 class ProductB : IProduct {
   public String ShipFrom () {
           return "from Spain";
   }
 }
 
 class DefaultProduct : IProduct {
   public String ShipFrom () {
           return "not available";
   }
 }

2.静态工厂

class Creator {
   public static  IProduct FactoryMethod(int month) {
     if (month >= 4 && month <=11)
       return new ProductA();
     else 
     if (month == 1 || month == 2 || month == 12)
       return new ProductB();
     else 
       return new DefaultProduct();
   }
 }


这个方式很简单,缺点就是无法扩展,需要if else判断或者swich等判断。视具体情况而定