Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Basically it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in "what we want to do with the resource". For example:</p> <pre><code>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 it executeWithFile("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 -&gt; System.out.println(s.read())); // Or with Java 8 Method reference: executeWithFile("filename.txt", ClassName::methodName); </code></pre> <p>The calling code doesn't need to worry about the open/clean-up side - it will be taken care of by <code>executeWithFile</code>.</p> <p>This was frankly painful in Java because closures were so wordy, starting with Java 8 lambda expressions can be implemented like in many other languages (e.g. C# lambda expressions, or Groovy), and this special case is handled since Java 7 with <code>try-with-resources</code> and <code>AutoClosable</code> streams.</p> <p>Although "allocate and clean-up" is the typical example given, there are plenty of other possible examples - transaction handling, logging, executing some code with more privileges etc. It's basically a bit like the <a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="noreferrer">template method pattern</a> but without inheritance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload