2015-09-07 11:44:36 -06:00
|
|
|
// patterns/strategy/StrategyPattern2.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-07-28 12:48:23 -06:00
|
|
|
// {java patterns.strategy.StrategyPattern2}
|
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
|
|
|
|
|
|
|
// "Context" is now incorporated:
|
|
|
|
class FindMinima2 {
|
2021-03-04 16:15:04 -07:00
|
|
|
private
|
2015-11-03 12:00:44 -08:00
|
|
|
Function<List<Double>, List<Double>> algorithm;
|
2015-06-15 17:47:35 -07:00
|
|
|
FindMinima2() { leastSquares(); } // default
|
|
|
|
// The various strategies:
|
|
|
|
void leastSquares() {
|
2015-11-03 12:00:44 -08:00
|
|
|
algorithm = (line) -> Arrays.asList(1.1, 2.2);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
void 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
|
|
|
}
|
|
|
|
void 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
|
|
|
}
|
2015-11-03 12:00:44 -08:00
|
|
|
List<Double> minima(List<Double> line) {
|
2015-06-15 17:47:35 -07:00
|
|
|
return algorithm.apply(line);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class StrategyPattern2 {
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void main(String[] args) {
|
2015-06-15 17:47:35 -07:00
|
|
|
FindMinima2 solver = new FindMinima2();
|
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));
|
2021-03-04 16:15:04 -07:00
|
|
|
solver.perturbation();
|
|
|
|
System.out.println(solver.minima(line));
|
2015-06-15 17:47:35 -07:00
|
|
|
solver.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]
|
2021-03-04 16:15:04 -07:00
|
|
|
[3.3, 4.4]
|
2015-11-03 12:00:44 -08:00
|
|
|
[5.5, 6.6]
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|