基本上,是在这种模式下,你编写一种方法来执行始终需要执行的操作,例如资源分配和清理,并使调用者传递“我们想对资源进行的操作”。例如:
public interface InputStreamAction{ void useStream(InputStream stream) throws IOException;}// Somewhere else public void executeWithFile(String filename, InputStreamAction action) throws IOException{ InputStream stream = new FileInputStream(filename); try { action.useStream(stream); } finally { stream.close(); }}// Calling itexecuteWithFile("filename.txt", new InputStreamAction(){ public void useStream(InputStream stream) throws IOException { // Code to use the stream goes here }});// Calling it with Java 8 Lambda expression:executeWithFile("filename.txt", s -> System.out.println(s.read()));// Or with Java 8 Method reference:executeWithFile("filename.txt", ClassName::methodName);调用代码无需担心打开/清理的一面,它将由处理
executeWithFile。
坦白说,这在Java中是很痛苦的,因为闭包是如此word,从Java 8 lambda表达式开始就可以像许多其他语言一样实现(例如
C#lambda表达式或
Groovy),并且这种特殊情况是从Java 7开始使用
try-with-resourcesand AutoClosable流处理的。
尽管“分配和清理”是给出的典型示例,但还有许多其他可能的示例-事务处理,日志记录,以更多特权执行某些代码等。它基本上有点类似于模板方法模式,但没有继承。



