【设计模式】策略模式

行为型设计模式: 策略模式 strategy

定义一系列的算法, 把他们一个个封装起来, 并且使他们可以相互替换

分离「策略」并使他们之间能互相快速切换。此外,这种模式是一种不错的继承替代方案(替代使用扩展抽象类的方式)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

interface Algorithm
{
public function calculate();
}

class StrategyAlgorithmA implements Algorithm
{
public function calculate()
{
echo "+";
}
}

class StrategyAlgorithmB implements Algorithm
{
public function calculate()
{
echo "-";
}
}

class client
{
public function getResult(Algorithm $algorithm)
{
return $algorithm->calculate();
}
}

$client = new Client();
$client = new Client();
echo $client->getResult(new StrategyAlgorithmA()) . PHP_EOL;
echo $client->getResult(new StrategyAlgorithmB()) . PHP_EOL;