OnJava8-Examples/patterns/strategy/StrategyPattern.java

61 lines
1.4 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/strategy/StrategyPattern.java
2015-06-15 17:47:35 -07:00
package patterns.strategy;
import java.util.function.*;
2015-11-03 12:00:44 -08:00
import java.util.*;
2015-06-15 17:47:35 -07:00
// The common strategy base type:
class FindMinima {
2015-11-03 12:00:44 -08:00
Function<List<Double>, List<Double>> algorithm;
2015-06-15 17:47:35 -07:00
}
// The various strategies:
class LeastSquares extends FindMinima {
LeastSquares() {
// Line is a sequence of points (Dummy data):
2015-11-03 12:00:44 -08:00
algorithm = (line) -> Arrays.asList(1.1, 2.2);
2015-06-15 17:47:35 -07:00
}
}
class Perturbation extends FindMinima {
Perturbation() {
2015-11-03 12:00:44 -08:00
algorithm = (line) -> Arrays.asList(3.3, 4.4);
2015-06-15 17:47:35 -07:00
}
}
class Bisection extends FindMinima {
Bisection() {
2015-11-03 12:00:44 -08:00
algorithm = (line) -> Arrays.asList(5.5, 6.6);
2015-06-15 17:47:35 -07:00
}
}
// The "Context" controls the strategy:
class MinimaSolver {
private FindMinima strategy;
public MinimaSolver(FindMinima strat) {
strategy = strat;
}
2015-11-03 12:00:44 -08:00
List<Double> minima(List<Double> line) {
2015-06-15 17:47:35 -07:00
return strategy.algorithm.apply(line);
}
void changeAlgorithm(FindMinima newAlgorithm) {
strategy = newAlgorithm;
}
}
public class StrategyPattern {
public static void main(String args[]) {
MinimaSolver solver =
new MinimaSolver(new LeastSquares());
2015-11-03 12:00:44 -08:00
List<Double> line = Arrays.asList(
2015-06-15 17:47:35 -07:00
1.0, 2.0, 1.0, 2.0, -1.0,
2015-11-03 12:00:44 -08:00
3.0, 4.0, 5.0, 4.0 );
System.out.println(solver.minima(line));
2015-06-15 17:47:35 -07:00
solver.changeAlgorithm(new Bisection());
2015-11-03 12:00:44 -08:00
System.out.println(solver.minima(line));
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-11-03 12:00:44 -08:00
[1.1, 2.2]
[5.5, 6.6]
2015-09-07 11:44:36 -06:00
*/