This allows utilities that rightly belong in the interface, which are typically things that manipulate that interface, or are general-purpose tools:
// onjava/Operations.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.
package onjava;
import java.util.*;
public interface Operations {
void execute();
static void runOps(Operations... ops) {
for (Operations op : ops) op.execute();
}
static void show(String msg) {
System.out.println(msg);
}
}
above code is a version of the Template Method design pattern.
// interfaces/Machine.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.
import java.util.*;
import onjava.Operations;
class Bing implements Operations {
public void execute() {
Operations.show("Bing");
}
}
class Crack implements Operations {
public void execute() {
Operations.show("Crack");
}
}
class Twist implements Operations {
public void execute() {
Operations.show("Twist");
}
}
public class Machine {
public static void main(String[] args) {
Operations.runOps(new Bing(), new Crack(), new Twist());
}
}
/* Output:
Bing
Crack
Twist
*/
Here you see the different ways to create Operations: an external class(Bing), an anonymous class, a method reference, and lambda expressions——which certainly appear to be the nicest solution here.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/onjava/Operations.java
3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/interfaces/Machine.java
本文通过实例展示了Java8中Lambda表达式的使用,包括匿名类、方法引用和Lambda表达式本身,同时介绍了如何利用这些特性实现模板方法设计模式。
1339

被折叠的 条评论
为什么被折叠?



