C#设计模式_创建型_FactoryMethod模式(learn from Lijianzhong & others)
Posted on 2007-01-31 15:35 taoeternal 阅读(212) 评论(0) 编辑 收藏 举报意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。
适用性:
- 当一个类不知道它所必须创建的对象的类的时候。
- 当一个类希望由它的子类来指定它所创建的对象的时候。
- 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
结构:
using System;
namespace DesignPattern
{
/// <summary>
/// FactoryMethod 的摘要说明。
/// </summary>
public abstract class AbstractCar
{
public abstract void Start();
public abstract void Run();
public abstract void Turn(Direction direction);
public abstract void Stop();
}
public class CarTestFramework
{
public void BuildTestContext(CarFactory carFactory)
{
AbstractCar c1 = carFactory.CreateCar();
AbstractCar c2 = carFactory.CreateCar();
AbstractCar c3 = carFactory.CreateCar();
AbstractCar c4 = carFactory.CreateCar();
}
public void DoTest(AbstractCar car)
{
car.Run();
}
public TestData GetTestData()
{
}
}
public abstract class CarFactory{
public abstract Car CreateCar();
}
public class HongqiCar: AbstractCar{
Engine engin1;
Engine engin2;
Engine engin3;
Engine engin4;
public override void Start(){}
public override void Run(){}
public override void Turn(Direction direction){}
public override void Stop(){}
}
public class DongfengCar : AbstractCar{
Engine engin1;
Engine engin2;
public override void Start(){}
public override void Run(){}
public override void Turn(Direction direction){}
public override void Stop(){}
}
public class HongqiCarFactory : CarFactory
{
public override AbstractCar CreateCar()
{
return new HongqiCar();
}
}
public class DongfengCarFactory : CarFactory
{
public override AbstractCar CreateCar()
{
return new DongfengCar();
}
}
class App
{
public static void Main(){
CarTestFramework carTestFamework = new CarTestFramework();
carTestFamework.BuildTestContext(new HongqiCarFactory());
CarTestFramework carTestFamework = new CarTestFramework();
carTestFamework.BuildTestContext(new DongfengCarFactory());
//Activator.CreateInstance(string TypeName)
}
}
public class FactoryMethod
{
public FactoryMethod()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
}
}