工厂模式

来源:互联网 发布:1.5cm胆结石知乎 编辑:程序博客网 时间:2024/04/30 07:51
  
Factory pattern 工厂模式
产品的诞生总是从单一向多样方向发展,工厂的发展也是一样,从简单的生产单一产品的简单工厂到生产多种产品的复杂工厂,当然,无论工厂如何复杂,最好不要将生长食品和生产机器放在同一工厂进行--------
话说从前有个资本家A,建了一个小型酱油,专门生产瓶装酱油。对于这样的工厂,可以描述如下。
抽象工厂
publicinterface Factory {
   publicvoid product();
}
酱油厂
publicclass soyFactory implements Factory {
   public soyFactory(){ 
   }
   publicvoid product(){
      System.out.println("一瓶酱油");
   }
}
后来慢慢的,人们不仅喜欢吃酱油,又喜欢吃醋,于是资本家又建了一个小型醋厂,专门生产醋,描述如下:
醋厂
publicclass VinegarFactory implements Factory {
   public VinegarFactory(){
   }
   publicvoid product(){
      System.out.println("一瓶醋");
   }
}
让我们看看A如何接待客户:
(1)如果顾客需要酱油,带到酱油厂灌一瓶。(不需指明灌一瓶酱油还是醋)
(2)如果顾客需要醋,带到醋厂灌一瓶。(也不需指明灌一瓶酱油还是醋)
过程描述
publicclass SellCustom{
      Factory factory ;
      public SellCustom(String str){
       if(str.equals("soy")){
           factory = new soyFactory() ; 
       }
       elseif(str.equals("vinegar")){
           factory = new VinegarFactory() ; 
          }
      }
      publicvoid giveCustom(){
       factory.product();//灌上一瓶
      }
}
测试结果
publicclass TestMain {
   publicstaticvoid main(String args[]){
//    出售酱油
      SellCustom cum1 = new SellCustom("soy") ;
       cum1.giveCustom() ;
//     出售醋
       SellCustom cum2 = new SellCustom("vinegar") ;
       cum2.giveCustom() ;
   }
}
输出     一瓶酱油
一瓶醋
终于有一天资本家发现,单独的酱油厂和醋厂实在没有什么必要,却反倒给自己和客户带来了很多麻烦,设想一个客户要购买酱油和醋两种产品就要奔走两个厂家,这实在有些不便。于是资本家将醋场和酱油场合成一个工厂,生产醋和酱油两种产品。让我们来看看改装后的工厂:
抽象工厂
publicinterface Factory {
   publicvoid product(String str);
}
具体工厂
publicclass FactFactory implements Factory {
   @Override
   publicvoid product(String str) {
      if("soy".equals(str)){
System.out.println("一瓶酱油");//      生产一瓶酱油
      }
      elseif("vinegar".equals(str)){
        System.out.println("一瓶醋");// 生产一瓶醋
      }
   }
}
接待客户类
publicclass SellCustom{
      Factory factory ;
      public SellCustom(String str){
       factory = new FactFactory() ;
       factory.product(str) ;
      }
}
测试
publicclass TestMain {
   publicstaticvoid main(String args[]){
//     出售酱油
      SellCustom cum1 = new SellCustom("soy") ;
//     出售醋
       SellCustom cum2 = new SellCustom("vinegar") ;
   }
}
输出结果    一瓶酱油
一瓶醋
 
对于初始的简单工程,由于工厂只能生产一种产品,所以产品直接与工厂的类型挂钩,所以在对工厂实例化的时候需要对工厂的构造函数进行传参,用于表明创建工厂的类型,是醋厂还是酱油厂。但在复杂工厂的模型下具体的产品类型不在于工厂的类型相挂钩,而是与工厂的方法相关,所以创建工厂的过程中,工厂类的构造函数不需要接受参数,而无论是酱油还是醋都将在同一工厂实例中进行生产,只是生产的方法不同巴了。因此后面的工厂模式又称之为工厂方法模式
原创粉丝点击