执行及描述任务-------策略模式

问题

如果类的相关操作需要根据环境变化而变化,那么可能会需要将类分解为子类,但是如果通过继承数创建多个子类的话就会产生一些问题,导致继承树体系中的每个分支中相关操作重复。当类必须支持同一个接口的多种实现时,最好的办法就是提取这些实现,并将他们防止在自己的类型中,而不是通过继承原有的类去支持这些实现。

uml

执行及描述任务-------策略模式

代码实现

<?php
//strategy.php 策略模式
abstract class Question{
    protected $prompt;
    protected $marker;
    function __construct($prompt,Marker $marker)
    {
        $this->prompt = $prompt;
        $this->marker = $marker;
    }

    function mark($response){
        return $this->marker->mark($response);
    }
}

//文本问题
class TextQuestion extends Question{

}

//语音问题
class AVquestion extends Question{

}

abstract class Marker{
    protected $test;

    abstract function mark($response);

    function __construct($test){
        $this->test = $test;
    }
}

class MarkLogicMarker extends Marker{
    function mark($response){

    }
}

class MatchMarker extends Marker{
    function mark($response){
        return ($this->test==$response);
    }
}

class RegexpMarker extends Marker{
    function mark($response){
        return (preg_match($this->test,$response));
    }
}






//client两个策略对象
$markers = array(
    new RegexpMarker('/f.ve/'),
    new MatchMarker('five')
);

foreach ($markers as $marker) {
    echo get_class($marker)."<br>";
    $questio = new TextQuestion("how many beans make five",$marker);
    foreach (array('five','four') as $response) {
        echo "	response: $response: ";
        if($questio->mark($response)){
            echo "well done<br>";
        }else{
            echo "never mind<br>";
        }
    }
}
?>