汽车接口ICar
大众车DaZhong、特斯拉Tesla继承自ICar
工厂接口IFactory
大众工厂DaZhongFactory,特斯拉工厂TeslaFactory继承自IFactory
使用:
ICar car=new TeslaFactory().GetCar();
在简单工厂模式的基础上改进,典型特征是存在实现同一个接口的多个工厂方法
public interface ICar
{
string Run();
}
public class Audi : ICar
{
public string Run()
{
return "奥迪行驶";
}
}
public class Benz : ICar
{
public string Run()
{
return "奔驰行驶";
}
}
public interface ICarFactory
{
ICar CreateCar();
}
public class AudiFactory : ICarFactory
{
public ICar CreateCar()
{
return new Audi();
}
}
public class BenzFactory : ICarFactory
{
public ICar CreateCar()
{
return new Benz();
}
}
调用:
ICar car1 = new AudiFactory().CreateCar();
car1.Run();
ICar car2 = new BenzFactory().CreateCar();
car2.Run();