php策略模式实现简单计算器

缘起宇轩阁 2019-12-21

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);

相关推荐