2015-05-05 11:20:13 -07:00
|
|
|
|
//: patterns/strategy/StrategyPattern.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-05-05 11:20:13 -07:00
|
|
|
|
package patterns.strategy;
|
2015-05-27 23:30:19 -07:00
|
|
|
|
import java.util.function.*;
|
|
|
|
|
import static net.mindview.util.PrintArray.*;
|
2015-05-05 11:20:13 -07:00
|
|
|
|
|
2015-05-27 23:30:19 -07:00
|
|
|
|
// The common strategy base type:
|
|
|
|
|
class FindMinima {
|
|
|
|
|
Function<double[], double[]> algorithm;
|
2015-05-05 11:20:13 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// The various strategies:
|
2015-05-27 23:30:19 -07:00
|
|
|
|
class LeastSquares extends FindMinima {
|
|
|
|
|
LeastSquares() {
|
|
|
|
|
// Line is a sequence of points (Dummy data):
|
|
|
|
|
algorithm = (line) -> new double[] { 1.1, 2.2 };
|
2015-05-05 11:20:13 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-05-27 23:30:19 -07:00
|
|
|
|
class Perturbation extends FindMinima {
|
|
|
|
|
Perturbation() {
|
|
|
|
|
algorithm = (line) -> new double[] { 3.3, 4.4 };
|
2015-05-05 11:20:13 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-05-27 23:30:19 -07:00
|
|
|
|
class Bisection extends FindMinima {
|
|
|
|
|
Bisection() {
|
|
|
|
|
algorithm = (line) -> new double[] { 5.5, 6.6 };
|
2015-05-05 11:20:13 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// The "Context" controls the strategy:
|
|
|
|
|
class MinimaSolver {
|
|
|
|
|
private FindMinima strategy;
|
|
|
|
|
public MinimaSolver(FindMinima strat) {
|
|
|
|
|
strategy = strat;
|
|
|
|
|
}
|
|
|
|
|
double[] minima(double[] line) {
|
2015-05-27 23:30:19 -07:00
|
|
|
|
return strategy.algorithm.apply(line);
|
2015-05-05 11:20:13 -07:00
|
|
|
|
}
|
|
|
|
|
void changeAlgorithm(FindMinima newAlgorithm) {
|
|
|
|
|
strategy = newAlgorithm;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class StrategyPattern {
|
|
|
|
|
public static void main(String args[]) {
|
|
|
|
|
MinimaSolver solver =
|
|
|
|
|
new MinimaSolver(new LeastSquares());
|
|
|
|
|
double[] line = {
|
|
|
|
|
1.0, 2.0, 1.0, 2.0, -1.0,
|
|
|
|
|
3.0, 4.0, 5.0, 4.0 };
|
|
|
|
|
printArray(solver.minima(line));
|
|
|
|
|
solver.changeAlgorithm(new Bisection());
|
|
|
|
|
printArray(solver.minima(line));
|
|
|
|
|
}
|
|
|
|
|
} ///:~
|