zoukankan      html  css  js  c++  java
  • PHP设计模式—策略模式

    定义:

    策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

    结构:

    • Strategy(策略类):定义所有支持的算法的公共接口。
    • ConcreteStrategy(具体策略类):封装了具体的算法或行为,继承于Strategy。
    • Context:Context上下文,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用。
    • Client:客户端代码。

    代码实例:

    /**
     * Strategy.php(策略类)
     * Class Strategy
     */
    abstract class Strategy
    {
        /**
         * 算法方法
         */
        abstract public function doInterface();
    }
    
    
    /**
     * ConcreteStrategyA.php(具体策略类)
     * Class ConcreteStrategyA
     */
    class ConcreteStrategyA extends Strategy
    {
        /**
         * 算法A具体实现方法
         */
        public function doInterface()
        {
            // TODO: Implement doInterface() method.
            return "使用算法A
    ";
        }
    }
    
    
    /**
     * ConcreteStrategyB.php(具体策略类)
     * Class ConcreteStrategyB
     */
    class ConcreteStrategyB extends Strategy
    {
        /**
         * 算法B具体实现方法
         */
        public function doInterface()
        {
            // TODO: Implement doInterface() method.
            return "使用算法B
    ";
        }
    }
    
    
    /**
     * Class Context
     */
    class Context
    {
        private $strategy;
    
        public function __construct(Strategy $strategy)
        {
            $this->strategy = $strategy;
        }
    
        /**
         * 根据具体的策略对象,调用相应的算法的方法
         */
        public function getInterface()
        {
            return $this->strategy->doInterface();
        }
    }

    客户端调用:

    // 算法A
    $strategyA = new Context(new ConcreteStrategyA());
    echo $strategyA->getInterface();
    echo '<br>';
    // 算法B
    $strategyB = new Context(new ConcreteStrategyB());
    echo $strategyB->getInterface();

    结果:

    使用算法A 
    使用算法B

     

    总结:

    • 策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。
    • 策略模式的 Strategy 类层次为 Context 定义了一系列的可供重用的算法或行为。继承有助于析取出这些算法中的公共功能。
    • 策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
  • 相关阅读:
    debian8 vga 文本模式下出现闪屏
    Delphi中根据分类数据生成树形结构的最优方法
    SQL获取每月、每季度、每年的最后一天记录
    Delphi实现树型结构
    Delphi中initialization和finalization
    Delphi 连接 Paradox
    delphi2007单个文件(pas)的控件安装
    Delphi安装*.pas扩展名的控件
    数据库组件介绍(Delphi)
    Delphi控件开发浅入深出(三)
  • 原文地址:https://www.cnblogs.com/woods1815/p/13700050.html
Copyright © 2011-2022 走看看