策略模式,策略就是算法和变化,策略模式就是对算法和变化的封装。是条件选择从客户端到服务端的转移。客户端与算法类的彻底隔离。

<?php
abstract class Strategy{
    public $paramA = '';
    public $paramB = '';
    public function getResult(){

    }
}
class AlgorithmA extends Strategy{
    public function algorithmA(){
        //算法A的实现
    }
}
class AlgorithmB extends Strategy{
    public function algorithmB(){
        //算法B的实现
    }
}
class AlgorithmC extends Strategy{
    public function algorithmC(){
        //算法C的实现
    }
}
?>

场景: 沃尔玛要做一个收银软件。有打8折,打5折等,有每满100减20等。

<?php
//抽象类
abstract class Pay{
    public $cash = '';
    public $total = '';
    public function getResult(){
        return $this->total;
    }
}
//打折
class Discount extends Pay{
    public function algorithm($cash, $discount=0.8){
        $this->total = $cash * $discount;
        return $this->getResult();
    }
}
//满多少减多少
class Reduce extends Pay{
    public function algorithm($cash, $satisfied=100, $returnCash=20){
        $this->total = $cash - floor($cash / $satisfied) * $returnCash;
        return $this->getResult();
    }
}
class Context{
    private $obj;
    public function __construct($type){
        switch($type){
            case 1:
                $this->obj = new Discount();
                break;
            case 2:
                $this->obj = new Reduce();
                break;
        }
    }
    public function algorithm(){
        $this->obj->algorithm();
    }
}
//客户端
$obj = new Context($_GET['type']);
echo $obj->algorithm();
?>

优点:客户端不需要做条件判断,而且仅仅需要认识一个类即可。乍一看和简单工厂很相似呢。

标签: PHP, 设计模式, 策略模式

添加新评论