策略模式

类图

2024072016402651.png

简单来说,策略模式把 if else 外置,让调用者决定传入什么策略,让代码符合开闭原则

最简单的策略模式

<?php
 
function echoString($string)
{
echo $string;
}
 
 
$lang = "en";
 
if ($lang == "en") {
$string = "Hello World";
echoString($string);
} elseif ($lang == "cn") {
$string = "你好,世界";
echoString($string);
} else {
// not supported language
}

echoString 接收一个字符串,客户端需要做的事情就是给出正确的策略(字符串)

把字符串封装为策略类

<?php
 
interface LanguageStrategy
{
public function getGreet(): string;
}
 
class EnglishStrategy implements LanguageStrategy
{
public function getGreet(): string
{
return "Hello World";
}
}
 
class ChineseStrategy implements LanguageStrategy
{
public function getGreet(): string
{
return "你好,世界";
}
}
 
function echoString(LanguageStrategy $language)
{
echo $language->getGreet();
}
 
$lang = "en";
 
if ($lang == "en") {
$strategy = new EnglishStrategy();
echoString($strategy);
} elseif ($lang == "cn") {
$strategy = new ChineseStrategy();
echoString($strategy);
} else {
// not supported language
return;
}

echoString 接收一个 LanguageStrategy 的实例,客户端需要做的事情就是给出正确的策略