php策略模式实现简单计算器
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>策略模式</title> </head> <body> <form action=‘./demo03.php‘ method="post"> <input type="text" name="op1"> <select name="op"> <option value="Add">+</option> <option value="Sub">-</option> <option value="Multi">*</option> <option value="div">/</option> </select> <input type="text" name="op2"> <p><input type="submit" name="" value="计算"></p> </form> </body> </html>
PHP:
<?php /** * 策略模式 * * 实现加减乘除 */ interface MathOp { public function calculation(float $num1, float $num2); } //策略一 加 class MathAdd implements MathOp { public function calculation(float $num1, float $num2) { // TODO: Implement calculation() method. return $num1+$num2; } } //策略二 减 class MathSub implements MathOp { public function calculation(float $num1, float $num2) { // TODO: Implement calculation() method. return $num1-$num2; } } //策略三 乘 class MathMulti implements MathOp { public function calculation(float $num1, float $num2) { // TODO: Implement calculation() method. return $num1*$num2; } } class MathDiv implements MathOp { public function calculation(float $num1, float $num2) { // TODO: Implement calculation() method. if( $num2 == 0) { return "被除数不能为0"; } return $num1/$num2; } } //环境角色 选择策略实现 class op { private $mathop; public function __construct(string $type) { $this->mathop = ‘Math‘.$type; } public function calc (float $num1, float $num2) { $cls = new $this->mathop; echo $cls->calculation($num1, $num2); } } $type = $_POST[‘op‘]; $op1 = $_POST[‘op1‘]; $op2 = $_POST[‘op2‘]; $obj = new op($type); $obj->calc($op1, $op2);
相关推荐
tracy 2020-08-31
natloc 2020-07-18
Codeeror 2020-06-28
baike 2020-06-14
Ingram 2020-06-04
yishujixiaoxiao 2020-06-03
走在IT的路上 2020-05-01
txlCandy 2020-04-20
清溪算法君老号 2020-04-14
wuxiaosi0 2020-02-22
shawsun 2020-02-14
spb 2020-02-14
xcguoyu 2020-02-14
wangxiaohua 2014-05-29
mbcsdn 2019-12-20
ustbfym 2019-12-01
明明蠢萌的夏木君 2010-06-21