笔记7:策略模式

和工厂模式很像

<?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 MathMnl 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 = 'add';

$cmath = new CMath($type);
echo $cmath->calc(3, 5), "\n";

$type = 'div';

$cmath = new CMath($type);
echo $cmath->calc(3, 5), "\n";