您的位置:首页 > 其它

创建型模式-简单工厂模式

2011-03-04 22:56 274 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 简单工厂模式
{

public class SimpleFactory
{

//将此函数改为静态的则变为了静态工厂方法
public IProduct CreateProduct(string productName)
{
switch (productName)
{
case "ProductA":
return new ProductA();
case "ProdcutB":
return new ProductB();
default:
throw new Exception("创建产品错误!");

}
}
}

public interface IProduct
{
void MustDoSomething();
}

public class ProductA : IProduct
{
public ProductA()
{ }
public void MustDoSomething()
{
//产品A的业务逻辑
}
}

public class ProductB : IProduct
{
public ProductB()
{

}
public void MustDoSomething()
{
//产品B的业务逻辑
}
}

public class AppClient
{
public static void Main(string[] args)
{
SimpleFactory afactory = new SimpleFactory();
IProduct  producta = afactory.CreateProduct("ProductA");
producta.MustDoSomething();//调用产品A的方法
IProduct productb = afactory.CreateProduct("ProdcutB");
productb.MustDoSomething();//将调用产品B的方法
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: