2012-02-17 62 views
2

在战略模式中,只做战略和技能中的一些逻辑可以保留一些自己的代码,它仍然是战略模式吗?战略模式,这是否正确

示例:我使用策略模式来影响元素在我的双向链表中的排序方式。 我所做的只是简单地将策略模式表示为如果它希望在给定元素之后插入,然后循环所有元素,然后在使策略模式发回错误的元素之前插入新元素。

或者是否必须在策略模式中进行所有排序才能使其成为“纯”策略模式?

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; 
     } 
    } 
} 

回答

2

它的清洁让你的策略算法在IInsertStrategy实施。想象一下,如果你想出第三种算法,但由于add函数中存在一些冲突而无法正确执行。您最终会触及代码的两个部分,这首先破坏了插入算法的抽象目的。

+0

这就是我在哪里想的,谢谢! – Androme 2012-02-17 06:56:47