[英]Confusion about Stateless Strategies
In Strategy design pattern, stateless strategies are mentioned. 在战略设计模式中,提到了无状态策略。 Could anyone please help me to understand it by answering following question:
有谁可以通过回答以下问题来帮助我理解它:
And I will highly appreciate if all this could be explained by giving an example. 如果所有这些都能通过举例说明,我将非常感激。
What is this stateless strategy? 这种无国籍战略是什么?
A stateless strategy is one where one "run" of the strategy does not affect another. 无国籍战略是战略的“运行”不会影响另一个战略的战略。
Here are two strategies for picking true
or false
: 以下是两种选择
true
或false
策略:
public final class FlipStrategy {
private boolean lastPick;
public boolean pick() {
lastPick = !lastPick;
return lastPick;
}
}
and... 和...
public final class RandomStrategy {
public boolean pick() {
return (new Random()).nextBoolean();
}
}
FlipStrategy
is a stateful-strategy. FlipStrategy
是一种有状态策略。 The result you get depends on previous results. 您获得的结果取决于以前的结果。
RandomStrategy
is a stateless-strategy. RandomStrategy
是一种无国籍策略。 The results you get are independent of each-other. 您获得的结果是彼此独立的。
What problem does it solve and how? 它解决了什么问题以及如何解决?
Stateless-strategies... 无状态的策略...
Where to use & not use this? 在哪里使用&不使用这个?
It is not always possible to use a stateless-strategy. 并非总是可以使用无国籍战略。 Imagine a strategy for a bouncer - it must remember how many people have already gone in to decide if more should be allowed.
想象一下保镖的策略 - 它必须记住已经有多少人已经决定是否应该允许更多。
Otherwise, stateless-strategies are better. 否则,无国籍战略会更好。
Sometimes, you can turn a stateful-strategy into a stateless one using a "context" object. 有时,您可以使用“上下文”对象将有状态策略转换为无状态策略。 A context object encodes all state relevant to a strategy into a parameter.
上下文对象将与策略相关的所有状态编码为参数。
In our previous example, the context might be: 在前面的示例中,上下文可能是:
public final class Context {
private final boolean lastPick;
public boolean getLastPick() {
return lastPick;
}
public Context(final boolean lastPick) {
this.lastPick = lastPick;
}
// hashCode etc...
}
Now FlipStrategy
can be implemented in a stateless way: 现在,
FlipStrategy
可以以无状态方式实现:
public final class FlipStrategy {
public boolean pick(final Context context) {
return !context.getLastPick();
}
}
The context object is also an arguably cleaner design. 上下文对象也是一个可以说是更清晰的设计。 The last pick is a property of the world, not the strategy, so it should not be a member of it.
最后一个选择是世界的属性,而不是策略,所以它不应该是它的成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.