简单工厂模式:通过传入不同的参数创造不同的工厂类,大大解耦了程序。
现在我们简单实现一个计算器类,通过传入参数和不同的运算符来实现。代码如下:
<?php Interface Calc { public function getResult(); } class Operation { protected $num1 = 0; protected $num2 = 0; protected $result = 0; public function setNum($num1, $num2) { $this->num1 = $num1; $this->num2 = $num2; } } class OperaAdd extends Operation implements Calc { public function getResult() { // TODO: Implement getResult() method. return $this->result = $this->num1 + $this->num2; } } class OperaMul extends Operation implements Calc { public function getResult() { // TODO: Implement getResult() method. return $this->result = $this->num1 * $this->num2; } } class OperaFactory { private static $obj; public static function createrOpera($type) { switch ($type) { case '+': self::$obj = new OperaAdd(); break; case '*': self::$obj = new OperaMul(); break; } return self::$obj; } } $obj = OperaFactory::createrOpera('+'); $obj->setNum(1, 2); echo $obj->getResult();