SyntaxHighlighter JS

2013-01-18

Strategy Pattern: Example

The Arrays.sort method and Comparator interface is a real world example of the Strategy pattern.

The Strategy pattern is composed of an interface defining exactly one method for the functional behavior.  The Comparator is an interface defining compare as the functional method.

Concrete implementations (function objects) can be defined for the Strategy interface, e.g. AscendingSortStrategy, DescendingSortStrategy.

  class AscendingSortStrategy implements Comparator<Integer> {
      private AscendingSortStrategy() { }
      public static final AscendingSortStrategy INSTANCE = 

        new AscendingSortStrategy();
      @Override
      public int compare(Integer i1, Integer i2) {
          final int int1 = i1;
          final int int2 = i2
          return  int1 - int2;
      }
  }

  class DescendingSortStrategy implements Comparator<Integer> {
     private DescendingSortStrategy() { }
     public static final DescendingSortStrategy INSTANCE =
       new DescendingSortStrategy();
     @Override
     public int compare(Integer i1, Integer i2) {
        final int int1 = i1;
        final int int2 = i2
        return int2 - int1;
     }
  }

To use, pass the concrete strategy to a method that can accept it.

  Integer[] integers = new Integer[] { 
    new Integer(5), new Integer(1), new Integer(7) ,
    new Integer(2)
  };

  Arrays.sort(integers, AscendingSortStrategy.INSTANCE);
  Arrays.sort(integers, DescendingSortStrategy.INSTANCE);

Object Oriented Principle:
Use interfaces instead of concrete implementation classes. 
Having Arrays.sort accept the Comparator interface allows the user flexibility to change the implementation details of the sort by creating new classes while keeping everything else the same.

No comments:

Post a Comment