策略模式-PHP设计模式

策略模式 

namespace strategy;

//策略模式,按照组合优于继承原则

//问题抽象类
abstract class Question {
    protected $promot;
    protected $marker;

    public function __construct($promot, Marker $marker)
    {
        $this->promot = $promot;
        $this->marker = $marker;
    }

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

class TextQuestion extends Question
{
    //处理文本问题特有的操作
}

class AVQuestion extends Question
{
    //处理语音问题特有的操作
}

//标记方式抽象类
abstract class Marker
{
    protected $type;
    protected $reponse;

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

    abstract public function mark($reponse);
}

class MarkLogicMarker extends Marker {
    private $engine;
    public function __construct($type)
    {
        parent::__construct($type);
    }

    public function mark($reponse)
    {
        //return $this->engine->evaluate($reponse);
        return true;
    }
}

class MatchMarker extends Marker
{
    public function mark($reponse)
    {
        return ($this->type == $reponse);
    }
}

class RegexpMarker extends Marker
{
    public function mark($reponse)
    {
        return (preg_match($this->type, $reponse));
    }
}

$markers = array(
    new RegexpMarker('/f.ve/'),
    new MatchMarker('five'),
    new MarkLogicMarker('$input equals "five"')
);

foreach ($markers as $marker) {
    var_dump(get_class($marker));
    $question = new TextQuestion("how many beans make five", $marker);
    foreach (array('five', 'four') as $reponse) {
        if ($question->mark($reponse)) {
            var_dump($reponse . ': well done');
        } else {
            var_dump($reponse . ': never mind');
        }
    }
}

/*
strategy\RegexpMarker
five: well done
four: never mind

strategy\MatchMarker
five: well done
four: never mind

strategy\MarkLogicMarker
five: well done
four: well done
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值