策略模式

<?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((int)$_POST['op1'],(int)$_POST['op2']);

 

posted @ 2019-05-30 15:21  zhang-san  阅读(96)  评论(0编辑  收藏  举报