使用策略模式,如何根据不同的参数来区别对待不同的执行方法?
3 个示例策略
public function execute(string $param1, string $param2)
{
// Do something specific to this method
//
// Do some generic things across all strategies
//
}
public function execute(string $param1)
{
// Do something specific to this method
//
// Do some generic things across all strategies
//
}
public function execute()
{
// Do something specific to this method
//
// Do some generic things across all strategies
}
他们都做了一些非常具体的事情,但为此需要不同的参数,然后他们做了一些每个策略都会做的通用事情。
最佳答案
Using the strategy pattern, how can treat different exectute methods differently in terms of them having different parameters?
如果你让它以这种方式工作,它就不会被认为是一个strategy
模式。您的客户知道不同的策略需要不同的参数这一事实使策略模式无效,因为这样客户就被假定知道(至少部分地)特定策略在内部做什么。
理解策略不应该选择性地接受参数。相反,它应该有选择地处理参数。因此,在您进一步阅读之前,请考虑我们现在拥有接受所有参数的所有策略。所以 Strategy1
只使用 param1
和 param2
而忽略 param3
,等等。
function execute(param1, param2, param3) { }
但是,如果您有更多参数,这会变得很丑陋。您可以改为拥有一个单独的 Parameter
类,并将此参数集合传递给每个策略。每个策略都将包含一个逻辑来获取和使用它需要的参数,并将忽略其余部分。
then they do something generic that every strategy will do
这就是您可以制定抽象策略的原因。它将包括抽象的 execute()
方法和每个具体策略将调用的自己的 execute()
方法。
总而言之,这是它的样子(不可编译的代码):
Main()
{
AbstractStrategy s = new ConcreteStrategy1();
s.Execute(parameters); // parameters -> collection
}
class AbstractStrategy {
Execute(parameters); // abstract
Execute() {} // not public
}
class ConcreteStrategy1 : AbstractStrategy {
override Execute(parameters) {
string pvalue1 = parameters.GetValue("param1");
base.Execute();
}
}
关于design-patterns - 具有不同方法签名的策略模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44378522/