Java 8 - include static methods inside interfaces
阿新 • • 發佈:2018-12-31
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