策略模式:定义一系列的算法,把每一个算法封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
类结构图:
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);
?>