我可能会做的(不知道具体细节)是为每个州构建一系列课程。然后按doStuff到那个班级:
class DoStuff { //The Client
protected $strategies = array();
public function addStrategy(iDoStuffStrategy $strategy) {
$this->strategies[] = $strategy;
}
public function doStuff ($a, $b, $c, $d) {
foreach ($this->strategies as $strategy) {
if ($strategy->test($a, $b, $c, $d)) {
return $strategy->doStuff();
}
}
throw new RuntimeException('Unhandleable Situation!');
}
}
interface iDoStuffStrategy {
// Return a bool if you can handle this situation
public function test($a, $b, $c, $d);
// Execute the implementation
public function doStuff();
}
然后,每个类将如下所示:
public function StrategyFoo implements iDoStuffStrategy {
public function test($a, $b, $c, $d) {
return $a && $b && $c && $d;
}
public function doStuff() {
//DoStuff!
}
}
public function StrategyBar implements iDoStuffStrategy {
public function test($a, $b, $c, $d) {
return !$a && $b && $c && $d;
}
public function doStuff() {
//DoStuff!
}
}
它基本上是一个实现策略模式 http://sourcemaking.com/design_patterns/strategy。这样做可以让您分离出决策树。