我在实施策略模式时遇到了一些麻烦
I'm having a little trouble implementing the Strategy pattern
我承认我在一个旨在每天显示不同消息(例如每日消息...)的程序中实现策略模式有点困难,但在特殊日期可能会有一些变体(例如圣诞快乐:来自一天的消息......),有人可以给我一个例子,说明我如何“可以”在 php 中实现这个实现吗?
我有一段时间没碰过 PHP,所以请原谅任何语法错误,但一般的想法是有一个 class,您可以在其中设置您想要的策略(在此案例,你想如何显示消息),然后根据是否是假期,你可以交换假期策略,比如:
class DailyMessage {
private $strategy;
private $message;
public function __construct(string $message, Strategy $strategy) {
$this->message = $message;
$this->strategy = $strategy;
}
public function setStrategy(Strategy $strategy) {
$this->strategy = $strategy;
}
public function getMessage() {
return $this->strategy->format($this->getMessage());
}
}
interface Strategy {
public function format($message);
}
class DefaultStrategy implements Strategy {
public function format($message) {
return $message;
}
}
class HolidayStrategy implements Strategy {
private $greeting;
__constructor($greeting) {
$this->greeting = $greeting;
}
public function format($message) {
return $greeting . ': ' . $message;
}
}
$dm = new DailyMessage($messageOfTheDay, new DefaultStrategy());
$holidays = ["Dec 25" => "Merry Christmas", "Oct 31" => "Happy Halloween"];
$today = date('M j');
if (array_key_exists($today, $holidays)) {
$dm->setStrategy(new HolidayStrategy($holidays[$today]));
}
echo $dm->getMessage();
我承认我在一个旨在每天显示不同消息(例如每日消息...)的程序中实现策略模式有点困难,但在特殊日期可能会有一些变体(例如圣诞快乐:来自一天的消息......),有人可以给我一个例子,说明我如何“可以”在 php 中实现这个实现吗?
我有一段时间没碰过 PHP,所以请原谅任何语法错误,但一般的想法是有一个 class,您可以在其中设置您想要的策略(在此案例,你想如何显示消息),然后根据是否是假期,你可以交换假期策略,比如:
class DailyMessage {
private $strategy;
private $message;
public function __construct(string $message, Strategy $strategy) {
$this->message = $message;
$this->strategy = $strategy;
}
public function setStrategy(Strategy $strategy) {
$this->strategy = $strategy;
}
public function getMessage() {
return $this->strategy->format($this->getMessage());
}
}
interface Strategy {
public function format($message);
}
class DefaultStrategy implements Strategy {
public function format($message) {
return $message;
}
}
class HolidayStrategy implements Strategy {
private $greeting;
__constructor($greeting) {
$this->greeting = $greeting;
}
public function format($message) {
return $greeting . ': ' . $message;
}
}
$dm = new DailyMessage($messageOfTheDay, new DefaultStrategy());
$holidays = ["Dec 25" => "Merry Christmas", "Oct 31" => "Happy Halloween"];
$today = date('M j');
if (array_key_exists($today, $holidays)) {
$dm->setStrategy(new HolidayStrategy($holidays[$today]));
}
echo $dm->getMessage();