forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrategyPattern.java
More file actions
68 lines (62 loc) · 1.7 KB
/
StrategyPattern.java
File metadata and controls
68 lines (62 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// patterns/strategy/StrategyPattern.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java patterns.strategy.StrategyPattern}
package patterns.strategy;
import java.util.function.*;
import java.util.*;
// The common strategy base type:
class FindMinima {
protected
Function<List<Double>, List<Double>> algorithm;
}
// The various strategies, each producing dummy data:
class LeastSquares extends FindMinima {
LeastSquares() {
// Line is a sequence of points:
algorithm = (line) -> Arrays.asList(1.1, 2.2);
}
}
class Perturbation extends FindMinima {
Perturbation() {
algorithm = (line) -> Arrays.asList(3.3, 4.4);
}
}
class Bisection extends FindMinima {
Bisection() {
algorithm = (line) -> Arrays.asList(5.5, 6.6);
}
}
// The "Context" controls the strategy:
class MinimaSolver {
private FindMinima strategy;
MinimaSolver(FindMinima strategy) {
this.strategy = strategy;
}
List<Double> minima(List<Double> line) {
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());
List<Double> line = Arrays.asList(
1.0, 2.0, 1.0, 2.0, -1.0,
3.0, 4.0, 5.0, 4.0 );
System.out.println(solver.minima(line));
solver.changeAlgorithm(new Perturbation());
System.out.println(solver.minima(line));
solver.changeAlgorithm(new Bisection());
System.out.println(solver.minima(line));
}
}
/* Output:
[1.1, 2.2]
[3.3, 4.4]
[5.5, 6.6]
*/