GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — OnJava8-Examples/patterns/strategy/StrategyPattern.java at master · lliittllee/OnJava8-Examples Expand file tree/ Copy pathStrategyPattern.javaMore file actions 64 lines (58 loc) · 1.56 KB / Copy pathStrategyPattern.javaFile metadata and controls64 lines (58 loc) · 1.56 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 // patterns/strategy/StrategyPattern.java // (c)2017 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 { Function<List<Double>, List<Double>> algorithm; } // The various strategies: class LeastSquares extends FindMinima { LeastSquares() { // Line is a sequence of points (Dummy data): 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 strat) { strategy = strat; } 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 Bisection()); System.out.println(solver.minima(line)); } } /* Output: [1.1, 2.2] [5.5, 6.6] */ |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |