策略模式,这个正确吗
在策略模式中只做策略中的一些逻辑和技能保留一些在我自己的代码中可以吗,这仍然是策略模式吗?
示例:我使用策略模式来影响元素在双向链表中的排序方式。 我所做的只是让策略模式指示是否希望插入到给定元素之后,然后循环所有元素,然后在使策略模式发送 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;
}
}
}
In the strategy pattern is it ok to only do some of the logic in the strategy and skill keep some on my own code, will it still be the strategy pattern?
Example: i use the strategy pattern to influence how elements are ordered in my Doubly linked list.
What i have done is simply to make the strategy pattern indicated if it wish to be inserted after a given element, and then loop all elements though, and then insert the new element before the element that made the strategy pattern send false back.
Or must all sorting be done in the strategy patter for it to be a "PURE" strategy pattern?
public interface IInsertStrategy<T> {
public boolean insertAfter(T insertValue, T testValue);
}
And the add code
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
IInsertStrategy
的实现中使用策略算法会更清晰。想象一下,如果您想出了第三种算法,但由于 add 函数中存在一些冲突而无法正确执行。您最终会触及代码的两部分,这首先违背了抽象插入算法的目的。It's cleaner to have your strategy algorithm in the implementation of
IInsertStrategy
. Imagine if you come up with a 3rd algorithm, but can't do it correctly because of some conflict in the add function. You end up touching two parts of your code which defeats the purpose of abstracting the insert algorithm in the first place.