php - 简化巨大的 if 语句 - 设计模式?

标签 php

我可能有一组如下所示的 if 语句:

if (a and b and c and d) {
  // do stuff
} else (!a and b and c and d) {
  // do something else
} else (!a and !b and c and D) {
  // do yet something else
} ...

等等所有可能的排列。

我想到了这样做:

switch ((a ? 'Y' : 'N') . (b ? 'Y' : 'N') . (c ? 'Y' : 'N') . (d ? 'Y' : 'N')) {

  case 'YNYN':
    // do stuff
    break;

  case 'NNNN':
    // etc.
    break;

}

有没有更好的办法?

最佳答案

我可能会做的(不知道细节)是为每个状态构建一系列类。然后将 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!
    }
}

它基本上是 Strategy Pattern 的一个实现.这样做可以让您分离出决策树。

关于php - 简化巨大的 if 语句 - 设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4961844/

相关文章:

php - 将 MYSQL DATE 格式转换为 php 的 STRING 格式

javascript - Codeigniter 在 foreach php 的 View html 中显示值

Java,发送URL请求并在回复之前关闭?

php - 如何在 Laravel 5 中使用 where 条件获取数据列表

php - 将 wiki 格式转换为 XHTML

php - 如何使用 jQuery 发送 JSON 对象数组

php - 对 PHP 项目进行基准测试的分步指南

php - 尝试获取友好的网址但没有任何反应

php - 通过在 mysql 查询后返回空标签,html 大小增加了三倍 |如何解决 - laravel

php - 无法弄清楚我的 SQL 语法有什么问题