战略模式,这是正确的

时间:2012-02-17 06:45:12

标签: java strategy-pattern

在策略模式中,只有策略和技能中的一些逻辑可以保留一些我自己的代码,它仍然是策略模式吗?

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

或者必须在战略模式中完成所有排序,使其成为“纯粹”策略模式?

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

1 个答案:

答案 0 :(得分:2)

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

相关问题