PHP 模式大全 - 策略模式

简介

策略模式可以在程序运作时更改其行为或算法,你可以通过切换策略来改变另一种算法,你需要一个接口来达代表这个策略类,然后在主要类当中去申明这个接口策略类,在需要变更时切换哪种策略来达成不同状态下所需要的功能。举个简单的例子:小明同学需要计算3加4等于几的问题? 可以有多种方式去算这个题目,方法一、 计算器输入计算 方法二、铅笔计算 …., 这种运算的方式就可以抽离出来作为策略。

实现方式

  1. 首先我们定义一个统一的策略调度器 Strategy.php
/**
 * Interface Strategy.
 */
interface Strategy
{
    /**
     * @return int
     */
     public function calculatePrice(int $price, int $count): int;
}
  1. 接下来逐个实现策略
    WithCalculator.php

    class WithCalculator  implements Strategy
    {
       public function calculate(int $a, int $b) 
      {
           return $a + $b;
      }
    }

    WithPencial.php

    class WithPencial implements Strategy
    {
       public function calculate(int $a, int $b) 
       {
            return $a + $b;
       }
    }
  2. 最后需要一个大类
    Calculate.php

    class Calculate
    {
      protected int $a;
      protected int $b;
      protected Strategy $strategy;
    
     public  function  __construct(int $a, int $b, Strategy $strategy) 
     { 
          $this->a = $a; 
          $this->b = $b; 
          $this->strategy = $strategy;
     }
    
    public function changeStrategy(Strategy $strategy)
    {
          $this->strategy = $strategy;
    }
    
    public function calculate() 
    {
          return $this->strategy->calculate($this->a, $this->b);
    }
    }

    测试

    class StrategyTest extends TestCase
    {
     /** * @test */
     public function test_strategy()
     {
         $calculate = new Calculate(3, 4, new WithCalculator); 
         $this->assertEquals(7, $calculate->calculate()); 
     }
    }
    

```

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!