• 设计模式之策略模式(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/>';
  • 相关阅读:
    百度之星资格赛1001——找规律——大搬家
    HDU1025——LIS——Constructing Roads In JGShining's Kingdom
    DP(递归打印路径) UVA 662 Fast Food
    递推DP UVA 607 Scheduling Lectures
    递推DP UVA 590 Always on the run
    递推DP UVA 473 Raucous Rockers
    博弈 HDOJ 4371 Alice and Bob
    DFS(深度) hihoCoder挑战赛14 B 赛车
    Codeforces Round #318 [RussianCodeCup Thanks-Round] (Div. 2)
    DP(DAG) UVA 437 The Tower of Babylon
  • 原文地址:https://www.cnblogs.com/zhouqi666/p/9166749.html
Copyright © 2020-2023  润新知