public class App { public void Main() { CarTestFramework carTestFramework = new CarTestFramework(); carTestFramework.BuildTestContext(new CarFactory()); //.... } }
public class HongqiCarFactory : AbstractCarFactory { public override AbstractCar CreateCar() { return new HongqiCar(); } }
现在客户程序就可以改成这样
1 2 3 4 5 6 7 8 9
public class App { public void Main() { CarTestFramework carTestFramework = new CarTestFramework(); carTestFramework.BuildTestContext(new HongqiCarFactory()); //.... } }
这样如果又有新的需求,比如要添加AutiCar进行测试,只需要做下面几步
1 添加AutiCar类继承AbstractCar类
1 2 3 4 5 6 7 8 9 10
public class AudiCar : AbstractCar { public override void Startup() { }
public override void Run() { }
public override void Turn(Direction direction) { }
public override void Stop() { } }
2 添加AudiCar的工厂类继承AbstractCarFactory类
1 2 3 4 5 6 7
public class AudiCarFactory : AbstractCarFactory { public override AbstractCar CreateCar() { return new AudiCar(); } }
3 客户程序稍作改动即可
1 2 3 4 5 6 7 8 9 10 11
public class App { public void Main() { CarTestFramework carTestFramework = new CarTestFramework(); carTestFramework.BuildTestContext(new HongqiCarFactory()); //添加一行代码即可 carTestFramework.BuildTestContext(new AudiCarFactory()); //.... } }
完整的代码
AbstractCar.cs
1 2 3 4 5 6 7 8 9 10
/// <summary> /// 抽象汽车类 /// </summary> public abstract class AbstractCar { public abstract void Startup(); public abstract void Run(); public abstract void Turn(Direction direction); public abstract void Stop(); }
AbstractCarFactory.cs
1 2 3 4 5 6 7
/// <summary> /// 抽象工厂类 /// </summary> public abstract class AbstractCarFactory { public abstract AbstractCar CreateCar(); }
/// <summary> /// 测试框架类 /// </summary> public class CarTestFramework { public void BuildTestContext(AbstractCarFactory abstractCarFactory) { AbstractCar car = abstractCarFactory.CreateCar(); }
public void DoTest(AbstractCarFactory abstractCarFactory) { //do something }
public void GetTestData(AbstractCarFactory abstractCarFactory) { //do something } }
App.cs
1 2 3 4 5 6 7 8 9 10 11 12
/// <summary> /// 客户类 /// </summary> public class App { public void Main() { CarTestFramework carTestFramework = new CarTestFramework(); carTestFramework.BuildTestContext(new HongqiCarFactory()); //.... } }