什么叫简单工厂模式? 简单工厂模式又叫静态工厂方法,专门定义一个类来负责创建其他类的实现,属于类的创建型模式。 计算器实现简单的工厂模式 <?php /** * 工厂类 */ class Factory { public static function create($operation) { switch($operation) { case "+": $result = new Add(); break; case "-": $result = new Sub(); break; case "*": $result = new Mul(); break; case "/": $result =new Div(); break; } return $result; } } /** * 运算类 */ abstract class Operation { protected $num1; protected $num2; public function set_num($num1,$num2) { $this->num1=$num1; $this->num2=$num2; } abstract function get_result(); } /** * 加法类 */ class Add extends Operation { public function get_result() { return $this->num1+$this->num2; } } /** * 减法类 */ class Sub extends Operation { public function get_result() { return $this->num1-$this->num2; } } /** * 乘法类 */ class Mul extends Operation { public function get_result() { return $this->num1*$this->num2; } } /** * 除法类 */ class Div extends Operation { public function get_result() { return $this->num1/$this->num2; } } $opear = Factory::create("+"); $opear->set_num(6,3); echo $opear->get_result(); echo "<br/>"; $opear = Factory::create("-"); $opear->set_num(6,3); echo $opear->get_result(); echo "<br/>"; $opear = Factory::create("*"); $opear->set_num(6,3); echo $opear->get_result(); echo "<br/>"; $opear = Factory::create("/"); $opear->set_num(6,3); echo $opear->get_result(); 显示结果: 9 3 18 2