zoukankan      html  css  js  c++  java
  • 设计模式之策略模式(php实现)

    github地址:https://github.com/ZQCard/design_pattern  
    /**
     * 在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
     * 在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。
     */

    (1)Strategy.class.php(策略抽象接口)

    <?php
    
    namespace Strategy;
    
    interface Strategy
    {
        public function doOperation(int $num1, int $num2):int;
    }

    (2)OperationAdd.class.php(加操作具体类)

    <?php
    
    namespace Strategy;
    
    class OperationAdd implements Strategy
    {
        public function doOperation(int $num1, int $num2):int
        {
            return $num1 + $num2;
        }
    }

    (3)OperationSubstract.class.php(减操作具体类)

    <?php
    
    namespace Strategy;
    class OperationSubstract implements Strategy
    {
    public function doOperation(int $num1, int $num2):int
    {
    return $num1 - $num2;
    }
    }

    (4)OperationMultiply.class.php(乘操作具体类)

    <?php
    
    namespace Strategy;
    
    class OperationMultiply implements Strategy
    {
        public function doOperation(int $num1, int $num2):int
        {
            return $num1 * $num2;
        }
    }

    (5)strategy.php (客户端类)

    <?php
    spl_autoload_register(function ($className){
        $className = str_replace('\','/',$className);
        include $className.".class.php";
    });
    
    use StrategyContext;
    use StrategyOperationAdd;
    use StrategyOperationSubstract;
    use StrategyOperationMultiply;
    
    $context = new Context(new OperationAdd());
    echo $context->execute(10, 5);
    echo '<br/>';
    
    $context = new Context(new OperationSubstract());
    echo $context->execute(10, 5);
    echo '<br/>';
    
    $context = new Context(new OperationMultiply());
    echo $context->execute(10, 5);
    echo '<br/>';
  • 相关阅读:
    Javascript--普通函数调用-涨工资计算函数
    Javascript--运算符判断成绩运算
    Javascript-闰年javascript的判断
    Javascript-逻辑判断或(&&)练习
    Javascript-短路 与(&&)
    UVALive6434_Number Assignment
    HDU4811_Ball
    HDU4810_Wall Painting
    HDU4803_Poor Warehouse Keeper
    HDU4802_GPA
  • 原文地址:https://www.cnblogs.com/zhouqi666/p/9166749.html
Copyright © 2011-2022 走看看