我的产品出厂工厂模式抽象工厂模式
public interface IProductFactory
{
void Drive(int miles);
}
我的汽车厂
public interface IVehicleFactory
{
IProdctFactory GetVehicle(string Vehicle);
}
产品自行车
class Bike:IProdctFactory
{
public void Drive(int miles)
{
Console.WriteLine("Drive the Bike : " + miles.ToString() + "km");
}
}
产品踏板车
class Scooter:IProdctFactory
{
public void Drive(int miles)
{
Console.WriteLine("Drive the Scooter : " + miles.ToString() + "km");
}
}
产品汽车
class Car:IProdctFactory
{
public void Drive(int miles)
{
Console.WriteLine("Drive the Car : " + miles.ToString() + "km");
}
}
产品吉普
class Jeep:IProdctFactory
{
public void Drive(int miles)
{
Console.WriteLine("Drive the Jeep : " + miles.ToString() + "km");
}
}
两个惠勒厂
public class TwoWheelerFactory : IVehicleFactory
{
public IProdctFactory GetVehicle(string Vehicle)
{
switch (Vehicle)
{
case "Scooter":
return new Scooter();
case "Bike":
return new Bike();
default:
throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
}
}
}
四轮汽车厂
class FourWheelerFactory:IVehicleFactory
{
public IProdctFactory GetVehicle(string Vehicle)
{
switch (Vehicle)
{
case "Car":
return new Car();
case "Jeep":
return new Jeep();
default:
throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
}
}
}
客户端
class Program
{
static void Main(string[] args)
{
IVehicleFactory twoWheelerfactory = new TwoWheelerFactory();
IProdctFactory scooter = twoWheelerfactory.GetVehicle("Scooter");
scooter.Drive(10);
IProdctFactory bike = twoWheelerfactory.GetVehicle("Bike");
bike.Drive(20);
IVehicleFactory fourWheelerFactory = new FourWheelerFactory();
IProdctFactory car = fourWheelerFactory.GetVehicle("Car");
car.Drive(100);
IProdctFactory jeep = fourWheelerFactory.GetVehicle("Car");
jeep.Drive(200);
Console.ReadKey();
}
}
在工厂模式中有两个具体的车辆类(TwoWheelerFactory,FourWheelerFactory)吗?
虽然我读了很多关于抽象工厂模式,我现在还不能确定它是什么:(有人可以帮助我将其转换为抽象工厂模式?
我读
Design Patterns: Abstract Factory vs Factory Method
和
http://www.dotnet-tricks.com/Tutorial/designpatterns/FUcV280513-Factory-Method-Design-Pattern---C
我不明白什么是IVehicleFactory给你,你似乎可以做实例化。另外,“驱动器”不是一种正常的工厂方法。总的来说,这看起来很奇怪。 – BradleyDotNET
PS我不禁注意到'miles.ToString()+“km”'看起来有点不对劲......实际上,它的偏差约为1.6倍。更何况距离不应该是一个整数。 – Aron
'IProductFactory'当然听起来不像'Drive's ... –