views:

120

answers:

2

I haven't studied design patterns, but I'm willing to bet that there is one for what I need to do. I'm running a set of different algorithms over a couple of trees. They all implement an interface:

public interface DistanceMetric {
    public double distance(AbstractTree<String> t1, AbstractTree<String> t2);
}

public class concreteDistanceAlgorithmV1 implements DistanceMetric{

    public double distance(AbstractTree<String> t1, AbstractTree<String> t2){
        // algorithm methods
        return distance; 
    }
}

However, suddenly I now need two versions of each algorithm one as above and the second is a variation which has the first tree preprocessed:

public interface DistanceMetricType2 {
    public double distance(AbstractTree<String> t);
}

public class concreteDistanceAlgorithmV2 implements DistanceMetricType2{

    private Object transformation1;

    public concreteDistanceAlgorithmV2(AbstractTree<String> t1){
        transformation1 = process(t1);
    }

    public double distance(AbstractTree<String> t2){

        Object transformation2 = process(t2);
        //algorithm involving both transformations
        return distance;
    }
}

There must be a better way than making two classes for every algorithm? Is this a use for the strategy pattern or similar? How can I modify what I have to make better use of good design principles?

+3  A: 

If you need to select the algorithm at runtime, check out the strategy pattern. The Strategy pattern provides an interface that all algorithms implement. Then, you can instantiate the proper algorithm and call its execute() method.

If you need to vary parts of an algorithm, check out the template method pattern. In template method, modifications to an algorithm override the appropriate methods to provide alternative ways of achieving the exact same goal. This is typically done by having an abstract class that is inherited.

Thomas Owens
A: 

I think you're right, this is a good time to make use of the strategy pattern.

chills42