<?php /** * 【策略模式】----和“简单工厂”模式很相似 * 根据不同运算符计算两个数的运算结果 * 常规方式就是判断运算符然后进行if...else的操作 * 现在使用“策略模式” */ header("Content-type: text/html; charset=utf-8"); if(isset($_POST['js']) && !empty($_POST['js'])){ /*接口,和四个真实计算器*/ interface Math{ public function calc($op1,$op2); } class Jia implements Math{ public function calc($op1, $op2){ return $op1+$op2; } } class Jian implements Math{ public function calc($op1, $op2){ return $op1-$op2; } } class Cheng implements Math{ public function calc($op1, $op2){ return $op1*$op2; } } class Chu implements Math{ public function calc($op1, $op2){ return $op1/$op2; } } /*封装一个虚拟计算器*/ class CMath{ protected $jisuan = null; //$objType 对应的真实计算器的 Jia/Jian/Cheng/Chu public function __construct($type){ if($type==1){ $objType = 'Jia'; }elseif($type==2){ $objType = 'Jian'; }elseif($type==3){ $objType = 'Cheng'; }elseif($type==4){ $objType = 'Chu'; }else{ exit('Error...'); } $this->jisuan = new $objType(); } public function jsq($num1,$num2){ return $this->jisuan->calc($num1,$num2); } } /*开始调用*/ $js = $_POST['js']; $cmath = new CMath($js); $res = $cmath->jsq($_POST['num1'], $_POST['num2']); echo $res; } ?> <form action="?" method="post"> <input type="text" name="num1"> <select name="js"> <option value="1">+</option> <option value="2">-</option> <option value="3">*</option> <option value="4">/</option> </select> <input type="text" name="num2"> <button type="submit">提交</button> </form>