This commit is contained in:
Bruce Eckel 2015-05-27 18:27:06 -07:00
parent 950a8b9303
commit f035b454c9
11 changed files with 374 additions and 0 deletions

View File

@ -0,0 +1,29 @@
//: innerclasses/ArgReturnReferences.java
// Demonstrates method references
import java.util.function.*;
import static net.mindview.util.Print.*;
class Y {
static Y create() { return new Y(); }
static void absorb(Y y) {}
static String transform1(Y y) { return "Y"; }
static String transform2(Y y, String s) {
return "Y" + " " + s;
}
}
public class ArgReturnReferences {
Supplier<Y> supply = Y::create;
Consumer<Y> consume = Y::absorb;
Function<Y, String> f1arg = Y::transform1;
BiFunction<Y, String, String> f2arg =
Y::transform2;
public static void main(String[] args) {
ArgReturnReferences arr =
new ArgReturnReferences();
Y y = arr.supply.get();
arr.consume.accept(y);
print(arr.f1arg.apply(y));
print(arr.f2arg.apply(y, "Howdy"));
}
} ///:~

View File

@ -0,0 +1,29 @@
//: innerclasses/CtorReference.java
// Demonstrates java.util.function
import java.util.function.*;
import static net.mindview.util.Print.*;
public class CtorReference {
public CtorReference() {
print("Inside CtorReference()");
}
public CtorReference(int i) {
print("Inside CtorReference(i)");
}
public CtorReference(int i, double d) {
print("Inside CtorReference(i, d)");
}
public static void main(String[] args) {
Supplier<CtorReference> cr0 =
CtorReference::new;
CtorReference r0 = cr0.get();
Function<Integer, CtorReference> cr1 =
CtorReference::new;
CtorReference r1 = cr1.apply(1);
BiFunction<Integer, Double, CtorReference> cr2 =
CtorReference::new;
CtorReference r2 = cr2.apply(1, 2.0);
}
} ///:~

View File

@ -0,0 +1,22 @@
//: innerclasses/MethodReferences.java
import java.util.*;
public class MethodReferences {
static class Description {
String describe;
public Description(String desc) {
describe = desc;
}
public void show() { System.out.println(describe); }
}
public static void main(String[] args) {
List<String> keys = Arrays.asList(
"Every", "Good", "Boy", "Deserves", "Fudge");
keys.forEach(System.out::println); // (1)
List<Description> descriptions = new ArrayList<>();
for(String k : keys)
descriptions.add(new Description(k));
descriptions.forEach(Description::show); // (2)
}
} ///:~

View File

@ -0,0 +1,31 @@
//: innerclasses/RunnableMethodReference.java
// Demonstrates method references
import static net.mindview.util.Print.*;
class External {
static void go() { print("External.go()"); }
}
public class RunnableMethodReference {
Runnable robject, rstatic, rexstatic;
void f() { print("f()"); }
static void g() { print("g()"); }
public void assign() {
robject = this::f;
rstatic = RunnableMethodReference::g;
rexstatic = External::go;
}
public void call() {
robject.run();
rstatic.run();
rexstatic.run();
}
public static void main(String[] args) {
RunnableMethodReference rmr =
new RunnableMethodReference();
rmr.assign();
rmr.call();
rmr.robject = rmr::f;
rmr.robject.run();
}
} ///:~

View File

@ -0,0 +1,23 @@
//: innerclasses/UnboundMethodReference.java
// Method reference without an object.
import java.util.*;
import java.util.function.*;
import static net.mindview.util.Print.*;
class X {
String f() { return "X.f()"; }
}
public class UnboundMethodReference {
public static void main(String[] args) {
Function<String, Integer> len = String::length;
print(len.apply("UnboundMethodReference"));
List<String> words =
Arrays.asList("Rain", "Spain", "Plain");
words.forEach(System.out::println);
Function<X, String> xfr = X::f;
print(xfr.apply(new X()));
}
} ///:~

View File

@ -0,0 +1,14 @@
//: net/mindview/util/PrintArray.java
// Display an array of double
package net.mindview.util;
public class PrintArray {
public static void printArray(double[] array) {
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if(i != array.length -1)
System.out.print(", ");
}
System.out.println();
}
} ///:~

View File

@ -0,0 +1,47 @@
//: patterns/CommandPattern2.java
// Using the Runnable functional interface
import java.util.*;
class Command2 {
public Runnable execute;
}
class Hello2 extends Command2 {
Hello2() {
execute = () -> System.out.print("Hello ");
}
}
class World2 extends Command2 {
World2() {
execute = () -> System.out.print("World! ");
}
}
class IAm2 extends Command2 {
IAm2() {
execute = () ->
System.out.print("I'm the command pattern!");
}
}
class Macro2 extends Command2 {
private List<Command2> commands =
new ArrayList<>();
public void add(Command2 c) { commands.add(c); }
Macro2() {
execute = () -> {
for(Command2 c: commands) c.execute.run();
};
}
}
public class CommandPattern2 {
public static void main(String args[]) {
Macro2 macro = new Macro2();
macro.add(new Hello2());
macro.add(new World2());
macro.add(new IAm2());
macro.execute.run();
}
} ///:~

View File

@ -0,0 +1,34 @@
//: patterns/CommandPattern3.java
// Just implement the Runnable interface!
import java.util.*;
class Hello3 implements Runnable {
public void run() { System.out.print("Hello "); }
}
class World3 implements Runnable {
public void run() { System.out.print("World! "); }
}
class IAm3 implements Runnable {
public void run() {
System.out.print("I'm the command pattern!");
}
}
class Macro3 implements Runnable {
public List<Runnable> commands = new ArrayList<>();
public void run() {
for(Runnable c: commands) c.run();
}
}
public class CommandPattern3 {
public static void main(String args[]) {
Macro3 macro = new Macro3();
macro.commands.add(new Hello3());
macro.commands.add(new World3());
macro.commands.add(new IAm3());
macro.run();
}
} ///:~

View File

@ -0,0 +1,49 @@
//: patterns/absfactory/GameEnvironment2.java
// Using the Supplier<> Functional Interface.
package patterns.absfactory;
import java.util.function.*;
class GameElementFactory2 {
Supplier<Player> player;
Supplier<Obstacle> obstacle;
}
// Concrete factories:
class KittiesAndPuzzles2
extends GameElementFactory2 {
KittiesAndPuzzles2() {
player = Kitty::new;
obstacle = Puzzle::new;
}
}
class KillAndDismember2
extends GameElementFactory2 {
KillAndDismember2() {
player = KungFuGuy::new;
obstacle = NastyWeapon::new;
}
}
public class GameEnvironment2 {
private Player p;
private Obstacle ob;
public GameEnvironment2(
GameElementFactory2 factory) {
p = factory.player.get();
ob = factory.obstacle.get();
}
public void play() {
p.interactWith(ob);
}
public static void main(String args[]) {
GameElementFactory2
kp = new KittiesAndPuzzles2(),
kd = new KillAndDismember2();
GameEnvironment2
g1 = new GameEnvironment2(kp),
g2 = new GameEnvironment2(kd);
g1.play();
g2.play();
}
} ///:~

View File

@ -0,0 +1,61 @@
//: patterns/chain/ChainOfResponsibility2.java
// Using the Functional interface.
package patterns.chain;
import java.util.*;
import java.util.function.*;
import static net.mindview.util.PrintArray.*;
class FindMinima2 {
public static Result leastSquares(double[] line) {
System.out.println("LeastSquares.algorithm");
boolean weSucceed = false;
if(weSucceed) // Actual test/calculation here
return new Result(new double[] { 1.1, 2.2 });
else // Try the next one in the chain:
return new Fail();
}
public static Result perturbation(double[] line) {
System.out.println("Perturbation.algorithm");
boolean weSucceed = false;
if(weSucceed) // Actual test/calculation here
return new Result(new double[] { 3.3, 4.4 });
else
return new Fail();
}
public static Result bisection(double[] line) {
System.out.println("Bisection.algorithm");
boolean weSucceed = true;
if(weSucceed) // Actual test/calculation here
return new Result(new double[] { 5.5, 6.6 });
else
return new Fail();
}
static List<Function<double[], Result>> algorithms =
Arrays.asList(
FindMinima2::leastSquares,
FindMinima2::perturbation,
FindMinima2::bisection
);
public static Result minima(double[] line) {
for (Function<double[], Result> alg : algorithms) {
Result result = alg.apply(line);
if(result.success)
return result;
}
return new Fail();
}
}
public class ChainOfResponsibility2 {
public static void main(String args[]) {
FindMinima solver = new FindMinima();
double[] line = {
1.0, 2.0, 1.0, 2.0, -1.0,
3.0, 4.0, 5.0, 4.0 };
Result result = solver.minima(line);
if(result.success)
printArray(result.line);
else
System.out.println("No algorithm found");
}
} ///:~

View File

@ -0,0 +1,35 @@
//: patterns/strategy/StrategyPattern2.java
package patterns.strategy;
import java.util.function.*;
import static net.mindview.util.PrintArray.*;
// "Context" is now incorporated:
class FindMinima2 {
Function<double[], double[]> algorithm;
FindMinima2() { leastSquares(); } // default
// The various strategies:
void leastSquares() {
algorithm = (line) -> new double[] { 1.1, 2.2 };
}
void perturbation() {
algorithm = (line) -> new double[] { 3.3, 4.4 };
}
void bisection() {
algorithm = (line) -> new double[] { 5.5, 6.6 };
}
double[] minima(double[] line) {
return algorithm.apply(line);
}
}
public class StrategyPattern2 {
public static void main(String args[]) {
FindMinima2 solver = new FindMinima2();
double[] line = {
1.0, 2.0, 1.0, 2.0, -1.0,
3.0, 4.0, 5.0, 4.0 };
printArray(solver.minima(line));
solver.bisection();
printArray(solver.minima(line));
}
} ///:~