原则思想:只管即便通过扩展来办理需求变革,而不是修正原有功能。描述 :一个功能在他的生命周期内 (开拓到删除)在不断到变革,既然变革是一定的。 那我们在设计的时候该当提高程序到稳定性与灵巧性。 //对修正关闭,对扩展开放优点 :可以为所欲为到插拔功能,而不影响现有到功能。
//打算基类 class Calculation { public $num1; public $num2; public function set_num1($num) { $this->num1 = $num; } public function set_num2($num) { $this->num2 = $num; } } //加法 class addition extends Calculation { public function compute() { return $this->num1 + $this->num2; } } //如果存在其他算法 在加即可 //如 + - / //实例化干系功能类 用那方法就实例话那个方法 class operation { private $operation = null; public function calculation($symbol,$num1,$num2){ switch ($symbol){ case "+" : $this->operation = new addition(); break; default : echo "未兼容"; break; } if (!$this->operation){ exit(); } $this->operation->set_num1($num1); $this->operation->set_num2($num2); return $this->operation; } } $symbol = "+"; $num1 = 1; $num2 = 2; $operation = new operation(); $ret = $operation->calculation($symbol,$num1,$num2); echo $ret->compute(),PHP_EOL;
