在策略模式中,只做策略中的一些逻辑和技能,保留一些在我自己的代码中可以吗,这仍然是策略模式吗?
示例:我使用策略模式来影响元素在双向链表中的排序方式。 我所做的只是让策略模式指示是否希望插入到给定元素之后,然后循环所有元素,然后在使策略模式发送 false 的元素之前插入新元素。
或者必须在策略模式中完成所有排序才能成为“纯粹”策略模式?
public interface IInsertStrategy<T> {
public boolean insertAfter(T insertValue, T testValue);
}
以及添加代码
public void add(T value)
{
DoublyLinkedNode<T> workingNode = head;
// Loop though nodes, to and with the tail
while(workingNode.next != null)
{
workingNode = workingNode.next;
/* Keep going until the strategy is not true any more
* or until we have the last node. */
if(workingNode.next == null ||
!insertStrategy.insertAfter(value, workingNode.value))
{
workingNode.previous.append(value);
break;
}
}
}
最佳答案
在 IInsertStrategy
的实现中使用策略算法会更清晰。想象一下,如果您想出了第三种算法,但由于 add 函数中存在一些冲突而无法正确执行。您最终会触及代码的两部分,这首先就违背了抽象插入算法的目的。
关于java - 策略模式,这个正确吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9324020/