|
| 1 | +//: patterns/chain/ChainOfResponsibility2.java |
| 2 | +// Using the Functional interface. |
| 3 | +package patterns.chain; |
| 4 | +import java.util.*; |
| 5 | +import java.util.function.*; |
| 6 | +import static net.mindview.util.PrintArray.*; |
| 7 | + |
| 8 | +class FindMinima2 { |
| 9 | + public static Result leastSquares(double[] line) { |
| 10 | + System.out.println("LeastSquares.algorithm"); |
| 11 | + boolean weSucceed = false; |
| 12 | + if(weSucceed) // Actual test/calculation here |
| 13 | + return new Result(new double[] { 1.1, 2.2 }); |
| 14 | + else // Try the next one in the chain: |
| 15 | + return new Fail(); |
| 16 | + } |
| 17 | + public static Result perturbation(double[] line) { |
| 18 | + System.out.println("Perturbation.algorithm"); |
| 19 | + boolean weSucceed = false; |
| 20 | + if(weSucceed) // Actual test/calculation here |
| 21 | + return new Result(new double[] { 3.3, 4.4 }); |
| 22 | + else |
| 23 | + return new Fail(); |
| 24 | + } |
| 25 | + public static Result bisection(double[] line) { |
| 26 | + System.out.println("Bisection.algorithm"); |
| 27 | + boolean weSucceed = true; |
| 28 | + if(weSucceed) // Actual test/calculation here |
| 29 | + return new Result(new double[] { 5.5, 6.6 }); |
| 30 | + else |
| 31 | + return new Fail(); |
| 32 | + } |
| 33 | + static List<Function<double[], Result>> algorithms = |
| 34 | + Arrays.asList( |
| 35 | + FindMinima2::leastSquares, |
| 36 | + FindMinima2::perturbation, |
| 37 | + FindMinima2::bisection |
| 38 | + ); |
| 39 | + public static Result minima(double[] line) { |
| 40 | + for (Function<double[], Result> alg : algorithms) { |
| 41 | + Result result = alg.apply(line); |
| 42 | + if(result.success) |
| 43 | + return result; |
| 44 | + } |
| 45 | + return new Fail(); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +public class ChainOfResponsibility2 { |
| 50 | + public static void main(String args[]) { |
| 51 | + FindMinima solver = new FindMinima(); |
| 52 | + double[] line = { |
| 53 | + 1.0, 2.0, 1.0, 2.0, -1.0, |
| 54 | + 3.0, 4.0, 5.0, 4.0 }; |
| 55 | + Result result = solver.minima(line); |
| 56 | + if(result.success) |
| 57 | + printArray(result.line); |
| 58 | + else |
| 59 | + System.out.println("No algorithm found"); |
| 60 | + } |
| 61 | +} ///:~ |
0 commit comments