PHP 模式大全 - 策略模式
简介
策略模式可以在程序运作时更改其行为或算法,你可以通过切换策略来改变另一种算法,你需要一个接口来达代表这个策略类,然后在主要类当中去申明这个接口策略类,在需要变更时切换哪种策略来达成不同状态下所需要的功能。举个简单的例子:小明同学需要计算3加4等于几的问题? 可以有多种方式去算这个题目,方法一、 计算器输入计算 方法二、铅笔计算 …., 这种运算的方式就可以抽离出来作为策略。
实现方式
- 首先我们定义一个统一的策略调度器 Strategy.php
/**
* Interface Strategy.
*/
interface Strategy
{
/**
* @return int
*/
public function calculatePrice(int $price, int $count): int;
}
接下来逐个实现策略
WithCalculator.phpclass 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; } }
最后需要一个大类
Calculate.phpclass 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 协议》,转载必须注明作者和本文链接
推荐文章: