【发布时间】:2019-11-25 00:26:56
【问题描述】:
以下问题中使用的设计模式如何是工厂方法?我怀疑它既不是工厂方法也不是抽象工厂。它是两者的混合体。
interface Vehicle { }
class Car implements Vehicle{ } // Oil Vehicles
class Bus implements Vehicle{ }
class ElectricCar implements Vehicle{ } // ElectricVehicles
class ElectricBus implements Vehicle{ }
interface VehicleFactory{
Vehicle make(int seats);
}
class OilVehicleFactory implements VehicleFactory{ // Oil vehicle Factory
@Override
Vehicle make(int seats){
if(seats > 5){
return new Bus();
}
else{
return new Car();
}
}
class ElectricVehicleFactory implements VehicleFactory{ // Electric Vehicle Factory
@Override
Vehicle make(int seats){
if(seats > 5){
return new ElectricBus();
}
else{
return new ElectricCar();
}
}
class Client{ // Cient Code
boolean isElectric;
void doSomething(){
VehicleFactory factory;
if(isElectric){
factory = new ElectricVehicleFactory();
}
else{
factory = new oilVehicleFactory();
}
Vehicle vehicle = factory.make(5);
}
我相信这不是工厂方法:
使用接口VehicleFactory(抽象工厂中使用)
正在打造油车、电动车等产品系列
它不使用继承。
出于同样的原因,我相信它是一种抽象工厂方法。但它不使用工厂的组合。
究竟是什么模式?
谢谢
【问题讨论】:
-
您需要做的第一件事是确定您使用的语言,并相应地标记
-
@TheGeneral 是不是很接近?另外,模式语言是特定的吗?
-
softwareengineering.stackexchange.com 更适合设计模式及其讨论
-
@TheGeneral 在引用其他网站时,指出cross-posting is frowned upon 通常会有所帮助
-
设计模式是对常见问题的通用解决方案。代码期望解决什么设计问题/意图/要求?
标签: java c# oop design-patterns factory-pattern