Search code examples
javadesign-patternsstrategy-pattern

Extending functionality of Strategy pattern


I am developing an app that compares files. I decided to use the Strategy design pattern, to handle different formats, so I have something like this:

public class Report {
   CompareStrategy strategy;
   ...
}


public interface CompareStrategy {
   int compare(InputStream A, InputStreamB);
}

Then, naturally I implement the compare method for different file formats.

Now suppose I wanted to add another method, that deals with certain restrictions for the comparison (e.g. omit a row in case of an Excel or csv file, or omit a node in XML).

Would it be better to:

  1. Add another method to the interface and every implementation (there are few for the moment)
  2. Write a new interface which inherits from CompareStrategy and then implement it?

The second question is: since the differences can be of various types - would it be OK to make a marker interface Difference to enable something like:

int compareWithDifferences(..., Iterable<Difference> differences);

and then go on defining what a difference means for the specific file format?


Solution

  • Now suppose I wanted to add another method, that deals with certain restrictions for the comparison (e.g. omit a row in case of an Excel or csv file, or omit a node in XML).

    Looks like you need the Template Pattern

    You can create some abstract class like

    public abstract class XMLCompareStrategy implements CompareStrategy {
    
        public int compare(InputStream A, InputStreamB) {
            // several steps
            customMethod(...);
            // more steps
        }
    
        protected abstract ... customMethod(...);
    
    }
    

    This way you can create several classes that have the main or core functionality and provide custom details for every situation