Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
- });
- //... chunk of init/preparation code ...
- task A
- //... chunk of cleanup/finishing code ...
- //... chunk of identical init/preparation code ...
- task B
- //... chunk of identical cleanup/finishing code ...
- //... chunk of identical init/preparation code ...
- task C
- //... chunk of identical cleanup/finishing code ...
- //... and so on.
- //pseudo-code:
- class DoTask()
- {
- do(task T)
- {
- // .. chunk of prep code
- // execute task T
- // .. chunk of cleanup code
- }
- };
- DoTask.do(task A)
- DoTask.do(task B)
- DoTask.do(task C)
- //-- the target class
- class Resource {
- def open () { // sensitive operation }
- def close () { // sensitive operation }
- //-- target method
- def doWork() { println "working";} }
- //-- the execute around code
- def static use (closure) {
- def res = new Resource();
- try {
- res.open();
- closure(res)
- } finally {
- res.close();
- }
- }
- //-- using the code
- Resource.use { res -> res.doWork(); }
Add Comment
Please, Sign In to add comment