factorymethod-avocados.cs

本文介绍了一个使用C#实现的工厂模式案例,通过该模式根据不同月份选择不同的产品供应商。案例展示了如何定义产品接口及其实现类,并通过创建者类来决定实例化哪个具体的产品类。
  using System;
  using System.Collections;

  class FactoryPattern {
 
  // Factory Method Pattern       Judith Bishop 2006
  //  Example of exporting from different suppliers
    
  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";
    }
  }

  class Creator {
    public  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();
    }
  }
 
    static void Main() {
      Creator c = new Creator();
      IProduct product;
        
      for (int i=1; i<=12; i++) {
        product = c.FactoryMethod(i);
        Console.WriteLine("Avocados "+product.ShipFrom());
      }
    }
  }
 
/* Output
Avocados from Spain
Avocados from Spain
Avocados not available
Avocados  from South Africa
Avocados  from South Africa
Avocados  from South Africa
Avocados  from South Africa
Avocados  from South Africa
Avocados  from South Africa
Avocados  from South Africa
Avocados  from South Africa
Avocados from Spain
*/
 

 

转载于:https://www.cnblogs.com/shihao/archive/2012/05/14/2500462.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值