PHP设计模式——策略模式

<?php
/**
 * 策略模式
 * 策略模式帮助构建的对象不必自身包含逻辑,而是能够根据需要利用其他对象中的算法
 * 
 * 在能够创建基于对象的,由自包含算法组成的可互换对象时,最佳的做法是使用策略模式 
 */
interface Math{
    function calc($op1,$op2);
}

class Add implements Math{
    public function calc($op1,$op2) {
        return $op1 + $op2;
    }
}

class Sub implements Math{
    public function calc($op1,$op2) {
        return $op1 - $op2;
    }
}

//策略类
class CMath{
    protected $_calc = NULL;
    public function __construct($type) {
        $this->_calc = new $type;
    }
    public function calc($op1,$op2) {
        return $this->_calc->calc($op1,$op2);
    }
}

//使用
$type  = 'Add';
$calc = new CMath($type);
$result = $calc->calc(1, 100);
echo '1 + 100 = '.$result.'<br>';

//使用
$type  = 'Sub';
$calc = new CMath($type);
$result = $calc->calc(1, 100);
echo '1 - 100 = '.$result;
原文地址:https://www.cnblogs.com/tlxma/p/5210704.html