Strategy: choosing the algorithm at run-time : Strategy Pattern « Design Pattern « Java Tutorial






interface Find {
  double[] algorithm(double[] line);
}

class FindMethodA implements Find {
  public double[] algorithm(double[] line) {
    return new double[] { 1 };
  }
}
class FindMethodB implements Find {
  public double[] algorithm(double[] line) {
    return new double[] { 2 };
  }
}

class FindMethodC implements Find {
  public double[] algorithm(double[] line) {
    return new double[] { 3 };
  }
}
class FindMethodD implements Find {
  public double[] algorithm(double[] line) {
    return new double[] { 4 };
  }
}
class MySolver {
  private Find strategy;
  public MySolver(Find strat) {
    strategy = strat;
  }
  double[] get(double[] line) {
    return strategy.algorithm(line);
  }
  void changeAlgorithm(Find newAlgorithm) {
    strategy = newAlgorithm;
  }
}

public class StrategyPattern {
  public static void main(String args[]) {
    MySolver solver = new MySolver(new FindMethodA());
    double[] line = { 1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0 };
    solver.get(line);
    solver.changeAlgorithm(new FindMethodC());
    solver.get(line);
  }
}








34.18.Strategy Pattern
34.18.1.Strategy: choosing the algorithm at run-time
34.18.2.Action with the Strategy Pattern