php策略模式
<?php //php策略模式 interface Math{ public function calc($op1,$op2); } class MathAdd implements Math{ public function calc($op1,$op2){ return $op1+$op2; } } class MathSub implements Math{ public function calc($op1,$op2){ return $op1-$op2; } } class MathMul implements Math{ public function calc($op1,$op2){ return $op1*$op2; } } class MathDiv implements Math{ public function calc($op1,$op2){ return $op1/$op2; } } //封装一个虚拟计算机 class CMath{ protected $calc=null; public function __construct($type){ $calc='Math'.$type; $this->calc=new $calc(); } public function calc($op1,$op2){ return $this->calc->calc($op1,$op2); } } $type=$_POST['op']; $cmath=new CMath($type); echo $cmath->calc($_POST['op1'],$_POST['op2']);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>策略模式</title> </head> <body> <form action='2.php' method="post"> <input type="text" name="op1"> <select name="op"> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="div">/</option> </select> <input type="text" name="op2"> <p><input type="submit" name="" value="计算"></p> </form> </body> </html>
策略模式实现简单的计算器功能