Search code examples
javastrategy-pattern

Strategy pattern, is this correct


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

Solution

  • 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.