策略模式

策略模式:定义一系列的算法,把每一个算法封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。

类结构图:

策略模式类图

php代码实现:

<?php
class CashSuper{
    function AcceptCash($money){
        return 0;
    }
}
class CashNormal extends CashSuper{
    function AcceptCash($money){
        return $money;
    }
}
class CashRebate extends CashSuper{
    public $discount = 0;
    function __construct($ds){
        $this -> discount = $ds;
    }
    function AcceptCash($money){
        return $money * $this -> discount;
    }

}
class  CashReturn extends CashSuper{
    public $total = 0, $ret = 0;
    function __construct($t, $r){
        $this -> total = $t;
        $this -> ret = $r;
    }
    function AcceptCash($money){
        if($money >= $this->total){
            return $money - $this -> ret;
        }else{
            return $money;
        }
    }
}
class CashContext{
    function __construct($csuper){
        $this -> cs = $csuper;
    }
    function GetRequest($money){
        return $this -> cs -> AcceptCash($money);
    }
}

fwrite(STDOUT, "money: ");
$money = trim(fgets(STDIN));
$strategy = array();
$strategy['1'] = new CashContext(new CashNormal());
$strategy['2'] = new CashContext(new CashRebate(0.8));
$strategy['3'] = new CashContext(new CashReturn(300,100));
fwrite(STDOUT, "type:[1]for normal,[2]for 80% discount [3]for 300 -100.");
$ctype = trim(fgets(STDIN));
if(array_key_exists($ctype,$strategy)){
    $cc = $strategy[$ctype];
}else{
    fwrite(STDOUT, "Undefine type.Use normal mode.");
    $cc = $strategy["1"];
}
echo $cc -> GetRequest($money);

?>

  

转载于:https://www.cnblogs.com/zhutianpeng/p/4232093.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值