C#中的代码
class Program
{
static void Main(string[] args)
{
var benzCar = new CarClient(new BenzCarFactory());
var bmwCar = new CarClient(new BmwCarFactory());
benzCar.BuildCar();
bmwCar.BuildCar();
}
}
public interface Wheel { }
public interface Door { }
public interface Body { }
public class BenzWheel : Wheel { }
public class BmwWheel : Wheel { }
public class HondaWheel : Wheel { }
public class BenzDoor : Door { }
public class BmwDoor : Door { }
public class HondaDoor : Door { }
public class BenzBody : Body { }
public class BmwBody : Body { }
public class HondaBody : Body { }
public interface CarFactory
{
Body BuildBody();
Wheel BuildWheel();
Door BuildDoor();
}
public class BenzCarFactory: CarFactory {
public Body BuildBody() { return new BenzBody(); }
public Wheel BuildWheel() { return new BenzWheel(); }
public Door BuildDoor() { return new BenzDoor(); }
}
public class BmwCarFactory : CarFactory
{
public Body BuildBody() { return new BmwBody(); }
public Wheel BuildWheel() { return new BmwWheel(); }
public Door BuildDoor() { return new BmwDoor(); }
}
public class HondaCarFactory : CarFactory
{
public Body BuildBody() { return new HondaBody(); }
public Wheel BuildWheel() { return new HondaWheel(); }
public Door BuildDoor() { return new HondaDoor(); }
}
public class CarClient
{
private CarFactory _carFactory;
public CarClient(CarFactory factory)
{
_carFactory = factory;
}
public void BuildCar()
{
_carFactory.BuildBody();
_carFactory.BuildDoor();
_carFactory.BuildWheel();
// Remaining Business logic to assemble the parts and build a car.
}
}
答案 0 :(得分:1)
它肯定似乎是有效的Abstract Factory Pattern - 您确保只有某些品牌的零件与某些品牌的汽车一起使用。
但是,我必须对你的班级设计感到不愉快。
车轮/门在功能上与一辆车无异。同样精确的车轮/轮胎可以用于数十种汽车模型线。车轮具有属性但功能相同。宝马无法在17英寸车轮上获得独家优势。
所以,你的抽象工厂实现工作做得很好:)但是继续处理你的对象设计。
有关抽象工厂模式的一个很好的例子,请看看Java如何使用UI工具包,并在其不存在的桌面应用程序世界中更改UI主题