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>";
            }
        }
    }
    ?>
  • 相关阅读:
    flex兼容写法
    多行文字,最后一行省略号(适用于移动端)
    checkbox样式修改
    响应式布局
    微信常用的页面跳转
    css小技巧(清除滚动条)
    JS学习---PHP浅识
    qml 画页迁移
    list滚动条Scroll 偏移和长度计算公式总结
    qml listview关键字高亮
  • 原文地址:https://www.cnblogs.com/rcjtom/p/6069333.html
Copyright © 2011-2022 走看看