学习的点点滴滴

Email : 107311278@qq.com
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

工厂方法(Factory Method)

Posted on 2013-02-20 11:25  v薛定谔的猫v  阅读(123)  评论(0)    收藏  举报

概念描述:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。

类图:

C#代码:

interface IProduct
{
  void productMethod();
}

class Product : IProduct
{
  public void productMethod()
  {
    Console.WriteLine("产品");
  }
}

interface IFactory
{
  IProduct createProduct();
}

class Factory : IFactory
{
  public IProduct createProduct()
  {
    return new Product();
  }
}

public class Client
{
  public static void main(String[] args)
  {
    IFactory factory = new Factory();
    IProduct prodect = factory.createProduct();
    prodect.productMethod();
  }
}