我需要创建一个策略模式,其中用户从二十或三十个独特策略对象的列表中选择四个策略。策略列表将随着项目的成熟而扩展,用户可以随时更改他们选择的策略。
我打算将他们选择的策略名称存储为字符串,然后使用类似这样的方法来加载与他们选择的字符串对应的策略类。
class StrategyManager { // simplified for the example
public $selectedStrategies = array();
public function __construct($userStrategies) {
$this->selectedStrategies = array(
'first' => new $userStrategies['first'],
'second' => new $userStrategies['second'],
'third' => new $userStrategies['third'],
'fourth' => new $userStrategies['fourth']
);
}
public function do_first() {
$this->selectedStrategies['first']->execute();
}
public function do_second() {
$this->selectedStrategies['second']->execute();
}
public function do_third() {
$this->selectedStrategies['third']->execute();
}
public function do_fourth() {
$this->selectedStrategies['fourth']->execute();
}
}
我试图避免一个大的 switch 语句。我担心的是,这似乎有点Stringly Typed
。有没有更好的方法来实现这个目标而不使用条件或大型 switch 语句?
BTW:用户在选择四种策略时没有输入字符串。我需要维护一个字符串列表以在选择框中呈现给用户,并在添加新策略对象时将新字符串添加到列表中。
解释
ircmaxell对我正在尝试做的事情表示了一些困惑。在上面的例子中,用户从一个列表中选择了四个策略,并将它们作为字符串数组传递给 StrategyManager 构造函数。相应的策略对象被创建并存储在一个内部数组中,$this->selectedStrategies
“first”、“second”、“third”和“fourth”是四种不同选择策略的内部数组的数组键。建立 StrategyManager 对象后,应用程序execute
在流程生命周期的不同时刻使用四种策略的方法。
所以,简而言之......每次应用程序需要执行策略编号“一”的方法时,它都会执行此操作,并且结果会根据用户为策略“一”选择的策略而有所不同