OnJava8-Examples/patterns/chain/ChainOfResponsibility.java

88 lines
2.1 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: patterns/chain/ChainOfResponsibility.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.chain;
2015-05-27 23:30:19 -07:00
import java.util.*;
import static net.mindview.util.PrintArray.*;
2015-05-05 11:20:13 -07:00
2015-05-27 23:30:19 -07:00
class Result {
boolean success;
double[] line;
public Result(double[] data) {
success = true;
line = data;
2015-05-05 11:20:13 -07:00
}
2015-05-27 23:30:19 -07:00
public Result() {
success = false;
line = new double[] {};
2015-05-05 11:20:13 -07:00
}
}
2015-05-27 23:30:19 -07:00
class Fail extends Result {}
interface Algorithm {
Result algorithm(double[] line);
}
class LeastSquares implements Algorithm {
public Result algorithm(double[] line) {
2015-05-05 11:20:13 -07:00
System.out.println("LeastSquares.algorithm");
boolean weSucceed = false;
if(weSucceed) // Actual test/calculation here
2015-05-27 23:30:19 -07:00
return new Result(new double[] { 1.1, 2.2 });
2015-05-05 11:20:13 -07:00
else // Try the next one in the chain:
2015-05-27 23:30:19 -07:00
return new Fail();
2015-05-05 11:20:13 -07:00
}
}
2015-05-27 23:30:19 -07:00
class Perturbation implements Algorithm {
public Result algorithm(double[] line) {
2015-05-05 11:20:13 -07:00
System.out.println("Perturbation.algorithm");
boolean weSucceed = false;
if(weSucceed) // Actual test/calculation here
2015-05-27 23:30:19 -07:00
return new Result(new double[] { 3.3, 4.4 });
else
return new Fail();
2015-05-05 11:20:13 -07:00
}
}
2015-05-27 23:30:19 -07:00
class Bisection implements Algorithm {
public Result algorithm(double[] line) {
2015-05-05 11:20:13 -07:00
System.out.println("Bisection.algorithm");
boolean weSucceed = true;
if(weSucceed) // Actual test/calculation here
2015-05-27 23:30:19 -07:00
return new Result(new double[] { 5.5, 6.6 });
2015-05-05 11:20:13 -07:00
else
2015-05-27 23:30:19 -07:00
return new Fail();
2015-05-05 11:20:13 -07:00
}
}
2015-05-27 23:30:19 -07:00
class FindMinima {
List<Algorithm> algorithms = Arrays.asList(
new LeastSquares(),
new Perturbation(),
new Bisection()
);
public Result minima(double[] line) {
for (Algorithm alg : algorithms) {
Result result = alg.algorithm(line);
if(result.success)
return result;
}
return new Fail();
2015-05-05 11:20:13 -07:00
}
}
public class ChainOfResponsibility {
public static void main(String args[]) {
2015-05-27 23:30:19 -07:00
FindMinima solver = new FindMinima();
2015-05-05 11:20:13 -07:00
double[] line = {
1.0, 2.0, 1.0, 2.0, -1.0,
3.0, 4.0, 5.0, 4.0 };
2015-05-27 23:30:19 -07:00
Result result = solver.minima(line);
if(result.success)
printArray(result.line);
else
System.out.println("No algorithm found");
2015-05-05 11:20:13 -07:00
}
} ///:~