代码编程之策略模式-php专题
何时使用策略模式
在实际工作中,可能会出现大量的switch和if判断,这种硬编码的方式不利于后续工作的拓展和维护,这时候最好的方式就是使用策略模式
一复杂业务场景示例
<?php
/**
* 策略模式 完整示例(按你笔记思路实现)
* 场景:电商首页,根据用户性别展示不同商品类目+广告
*/
// 1. 定义策略接口(核心:统一行为规范)
interface UserStrategy
{
public function showCategory(); // 展示商品类目
public function showAd(); // 展示广告
}
// 2. 实现男性策略(继承接口,封装男性行为)
class MaleUserStrategy implements UserStrategy
{
public function showCategory()
{
return "展示:数码、汽车、运动类目";
}
public function showAd()
{
return "展示:数码产品、汽车广告";
}
}
// 3. 实现女性策略(继承接口,封装女性行为)
class FemaleUserStrategy implements UserStrategy
{
public function showCategory()
{
return "展示:美妆、服饰、母婴类目";
}
public function showAd()
{
return "展示:美妆产品、服饰广告";
}
}
// 4. 上下文类(核心:持有策略对象,对外提供统一调用入口)
class UserContext
{
private $strategy; // 策略对象属性
// 注入策略对象(依赖注入,解耦)
public function __construct(UserStrategy $strategy)
{
$this->strategy = $strategy;
}
// 对外统一方法:执行策略行为
public function showPage()
{
$category = $this->strategy->showCategory();
$ad = $this->strategy->showAd();
return "首页展示:{$category} | {$ad}";
}
}
// 5. 客户端调用(根据性别选择策略,无switch/if硬编码)
// 模拟男性用户
$maleContext = new UserContext(new MaleUserStrategy());
echo $maleContext->showPage();
echo PHP_EOL;
// 模拟女性用户
$femaleContext = new UserContext(new FemaleUserStrategy());
echo $femaleContext->showPage();
echo PHP_EOL;
// 扩展:新增儿童策略(只需新增策略类,无需修改原有代码)
class ChildUserStrategy implements UserStrategy
{
public function showCategory()
{
return "展示:玩具、绘本、童装类目";
}
public function showAd()
{
return "展示:玩具、儿童用品广告";
}
}
// 调用儿童策略
$childContext = new UserContext(new ChildUserStrategy());
echo $childContext->showPage();
2026/2/2大约 4 分钟
