zoukankan      html  css  js  c++  java
  • 执行及描述任务-------策略模式

    问题

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

    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>";
            }
        }
    }
    ?>
  • 相关阅读:
    [函數] Firemonkey Android 取得系统参数设定的字型大小
    [示例] 访问类的私有属性
    [修正] 移动平台曲线不平滑的问题(如:TRectangle, TPath...等)
    [修正] Firemonkey TSelection 控件等比缩放时,左下角拉动问题
    [修正] iOS 10 使用相机及相簿闪退的问题修正
    报表之表头
    报表字段刷新
    tfs解除锁
    sql server中排名的问题
    TFS查询无法在Excel中打开
  • 原文地址:https://www.cnblogs.com/rcjtom/p/6069333.html
Copyright © 2011-2022 走看看