应用场景
在不确定有多少种操作的时候;
比如说运算符号 + - * / ;
结构
1个工厂;
1个 interface 或者 abstract 产品父类;
多个实现 interface 或者继承 abstract 的具体产品类;
<?php /** * 用来创建各个运算的实例. * * 开放封闭原则简单来说就是对扩展开放对修改封闭; * 理想情况下我们是不应该再改动 Factory 类的; * 增加新运算应该使用扩展的方式; */ class Factory { public function getInstance($operate) { switch ($operate) { case '+': $instance = new Add(); break; case '-': $instance = new Sub(); break; case '*': $instance = new Mul(); break; case '/': $instance = new Div(); break; default: throw new InvalidArgumentException('暂不支持此运算符'); } return $instance; } } abstract class Operation { protected $param1 = 0; protected $param2 = 0; abstract public function getResult(); public function setParam1($param) { $this->param1 = $param; } public function setParam2($param) { $this->param2 = $param; } } class Add extends Operation { public function getResult() { return $this->param1 + $this->param2; } } class Sub extends Operation { public function getResult() { return $this->param1 - $this->param2; } } class Mul extends Operation { public function getResult() { return $this->param1 * $this->param2; } } class Div extends Operation { public function getResult() { if ($this->param2 == 0) { throw new InvalidArgumentException('除数不能为0'); } return $this->param1 / $this->param2; } } $factory = new Factory(); $operation = $factory->getInstance('+'); $operation->setParam1(1); $operation->setParam2(2); $result = $operation->getResult(); var_dump($result);
参考文档:https://baijunyao.com/article/161