php strategy pattern simple calculator

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
/**
 * Strategy Mode
 *
 * Implement arithmetic
 */

interface MathOp
{
    public function calculation(float $num1, float $num2);
}

// strategy plus a 
class MathAdd the implements MathOp
{
    public function calculation(float $num1, float $num2)
    {
        // TODO: Implement calculation() method.
        return $num1+$num2;
    }
}

// strategy two minus 
class MathSub the implements MathOp
{
    public function calculation(float $num1, float $num2)
    {
        // TODO: Implement calculation() method.
        return $num1-$num2;
    }
}

// strategy three by 
class MathMulti the 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)
    {
        // . The TODO: Implement Calculation () Method 
        IF ( $ num2 == 0 ) {
             return "dividend is not 0" ;
        }
        return $num1/$num2;
    }
}

// environmental policy implementation role selection 
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 [ 'on' ];
$ op1   = $ _POST [ "OP-1" ];
$ op2   = $ _POST [ "op2" ];

$ obj   = new on ( $ type );
$ obj -> calc ( $ op1 , $ op2 );

Guess you like

Origin www.cnblogs.com/zhangxiaoj/p/12077411.html