【策略模式】不同的时间用不同的规则优先考虑策略模式

记录策略模式,与简单工厂模式相互结合,降低代码之间的耦合

案列:超市收银软件系统,需求:满减,打折。。。各种优惠活动

5个类

  1. CountP
  2. Count
  3. Rabate
  4. Ret
  5. Cash
/**
* 父类
*/
abstract
class CountP { abstract public function getCash($money); }
/**
 * Class Count
 * @package Home\Driver\Sum
 * 正常计算类
 */
class Count extends CountP {
    public function getCash($money)
    {
        return $money;
    }
}
/**
 * Class Rabate
 * @package Home\Driver\Sum
 * 打折计算类
 */
class Rabate extends CountP {
    public $d = 1;

    public function __construct($dis)
    {
        $this->d = $dis;
    }

    public function getCash($money)
    {
        return $money * $this->d;
    }
}
/**
 * Class Ret
 * @package Home\Driver\Sum
 * 满减计算类
 */
class Ret extends CountP {
    public $moneyCondition = 0;
    public $moneyReturn = 0;

    public function __construct($moneyCondition,$moneyReturn)
    {
        $this->moneyCondition = $moneyCondition;
        $this->moneyReturn = $moneyReturn;
    }

    public function getCash($money)
    {
        if($money>=$this->moneyCondition){
            $money = $money-floor($money/$this->moneyCondition)*$this->moneyReturn;
        }
        return $money;
    }
}
/**
 * Class Cash
 * @package Home\Driver
 * 工厂类
 */
class Cash{
    public $obj = null;

    public function __construct($type)
    {
        switch ($type){
            case '正常收费':
                $this->obj = new Count();
                break;
            case '8折':
                $this->obj = new Rabate(0.8);
                break;
            case '满300减100':
                $this->obj = new Ret(300,100);
                break;
            default:
                throw_exception('类型错误');
                break;
        }
    }

    public function getAcceptCash($money){
        return $this->obj->getCash($money);
    }
}
/**
 * Class SumController
 * @package Home\Controller
 * 客户端
 */
class SumController extends Controller {

    public function index(){
        $countSum = new Cash('满300减100');
        $count = $countSum->getAcceptCash(400);
        echo $count;
    }
}
原文地址:https://www.cnblogs.com/huanhang/p/6037580.html