有没有一种设计模式可以阻止类方法在一个或多个需求出现之前运行?
举个例子,一辆汽车要发动起来,它需要汽油,点火钥匙,然后转动钥匙。
如何解决依赖需求(和必要的顺序)的问题,没有钥匙点火就不会启动,如果没有插入钥匙就不会转动。
下面是我知道的两种方法,它们都有缺陷:
void startCar()
if checkPetrol()
if checkKeyIn()
if checkKeyTurn()
startEngine()也可以使用switch语句,但也需要进行大量检查。
怎么解决这个问题呢?
发布于 2014-11-27 01:14:01
也许还有很多其他更合适的解决方案,但Observer pattern可以在这里使用。实际上,它将允许您定义对象之间的依赖关系,以便当一个对象更改状态时,它的所有依赖项都会被通知并自动更新。我正在考虑将它与Facade design pattern (只有startCar()是公共的)结合起来,并进行适当的异常处理:
void startCar(){
if (checkPetrol()){
if (checkKeyIn()){
if (checkKeyTurn()){
startEngine()
}else{
throw new CarCustomException("You need to turn the key in order to start.");
}
}else{
throw new CarCustomException("Car can't start without a key.");
}
}else{
throw new CarCustomException("Not enough fuel.");
}
}https://stackoverflow.com/questions/27134421
复制相似问题