推荐答案
// www.javascriptcn.com code example
<?php
interface Strategy {
public function execute($a, $b);
}
class AddStrategy implements Strategy {
public function execute($a, $b) {
return $a + $b;
}
}
class SubtractStrategy implements Strategy {
public function execute($a, $b) {
return $a - $b;
}
}
class Context {
private $strategy;
public function __construct(Strategy $strategy) {
$this->strategy = $strategy;
}
public function executeStrategy($a, $b) {
return $this->strategy->execute($a, $b);
}
}
// 使用示例
$context = new Context(new AddStrategy());
echo $context->executeStrategy(5, 3); // 输出 8
$context = new Context(new SubtractStrategy());
echo $context->executeStrategy(5, 3); // 输出 2本题详细解读
策略模式的定义
策略模式(Strategy Pattern)是一种行为设计模式,它允许你定义一系列算法,并将每个算法封装起来,使它们可以互换使用。策略模式使得算法可以独立于使用它的客户端而变化。
实现步骤
- 定义策略接口:首先定义一个策略接口(
Strategy),该接口声明了所有具体策略类必须实现的方法(如execute)。 - 实现具体策略类:创建多个具体策略类(如
AddStrategy和SubtractStrategy),这些类实现了策略接口,并提供了具体的算法实现。 - 定义上下文类:创建一个上下文类(
Context),该类持有一个策略对象的引用,并提供一个方法来执行策略。 - 客户端使用:客户端代码通过创建上下文对象并传入具体的策略对象来使用策略模式。上下文对象在执行时调用策略对象的
execute方法。
代码解析
- 策略接口:
Strategy接口定义了一个execute方法,所有具体策略类都必须实现这个方法。 - 具体策略类:
AddStrategy和SubtractStrategy分别实现了加法和减法的算法。 - 上下文类:
Context类持有一个策略对象,并通过executeStrategy方法来执行策略。 - 客户端代码:通过创建不同的策略对象并传递给上下文对象,客户端可以灵活地切换不同的算法。
优点
- 灵活性:策略模式允许在运行时动态地改变对象的行为。
- 可扩展性:可以轻松地添加新的策略类,而不需要修改现有的代码。
- 解耦:将算法的实现与使用算法的代码分离,使得代码更加模块化。
适用场景
- 当一个系统需要动态地在几种算法中选择一种时。
- 当一个类定义了多种行为,并且这些行为在这个类的操作中以多个条件语句的形式出现时。
- 当不希望客户端知道复杂的、与算法相关的数据结构时。