行为型设计模式 - 策略 Strategy
作者:菜皮日记
- 2023-09-08 北京
本文字数:1001 字
阅读完需:约 3 分钟
简介
一组实现了同一个策略接口的策略,可以随时指定用哪一种策略完成业务。
策略模式其实跟桥接模式很像,都是通过持有另一个对象,达到组合的效果。
角色
Context 上下文
可设置使用的 Strategy
抽象 Strategy
具体 Strategy
类图
如图,Context 使用 setStrategy 方法设置当前使用的策略,在 doSomething 中,调用策略的 execute 方法,实现动态使用策略。
类图
代码
class Context
{
private $strategy;
public function __construct(Strategy $strategy)
{
$this->strategy = $strategy;
}
public function setStrategy(Strategy $strategy)
{
$this->strategy = $strategy;
}
public function doSomeBusinessLogic(): void
{
echo "Context: Sorting data using the strategy (not sure how it'll do it)\n";
$result = $this->strategy->doAlgorithm(["a", "b", "c", "d", "e"]);
echo implode(",", $result) . "\n";
}
}
interface Strategy
{
public function doAlgorithm(array $data): array;
}
class ConcreteStrategyA implements Strategy
{
public function doAlgorithm(array $data): array
{
sort($data);
return $data;
}
}
class ConcreteStrategyB implements Strategy
{
public function doAlgorithm(array $data): array
{
rsort($data);
return $data;
}
}
$context = new Context(new ConcreteStrategyA());
echo "Client: Strategy is set to normal sorting.\n";
$context->doSomeBusinessLogic();
echo "Client: Strategy is set to reverse sorting.\n";
$context->setStrategy(new ConcreteStrategyB());
$context->doSomeBusinessLogic();
复制代码
output:
Client: Strategy is set to normal sorting.
Context: Sorting data using the strategy (not sure how it'll do it)
a,b,c,d,e
Client: Strategy is set to reverse sorting.
Context: Sorting data using the strategy (not sure how it'll do it)
e,d,c,b,a
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 3
菜皮日记
关注
全干程序员 2018-08-08 加入
还未添加个人简介
评论