code_junkie

What is the “Execute Around” idiom?

Nov 12th, 2011
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. public interface InputStreamAction
  2. {
  3. void useStream(InputStream stream) throws IOException;
  4. }
  5.  
  6. // Somewhere else
  7.  
  8. public void executeWithFile(String filename, InputStreamAction action)
  9. throws IOException
  10. {
  11. InputStream stream = new FileInputStream(filename);
  12. try {
  13. action.useStream(stream);
  14. } finally {
  15. stream.close();
  16. }
  17. }
  18.  
  19. // Calling it
  20. executeWithFile("filename.txt", new InputStreamAction()
  21. {
  22. public void useStream(InputStream stream) throws IOException
  23. {
  24. // Code to use the stream goes here
  25. }
  26. });
  27.  
  28. //... chunk of init/preparation code ...
  29. task A
  30. //... chunk of cleanup/finishing code ...
  31.  
  32. //... chunk of identical init/preparation code ...
  33. task B
  34. //... chunk of identical cleanup/finishing code ...
  35.  
  36. //... chunk of identical init/preparation code ...
  37. task C
  38. //... chunk of identical cleanup/finishing code ...
  39.  
  40. //... and so on.
  41.  
  42. //pseudo-code:
  43. class DoTask()
  44. {
  45. do(task T)
  46. {
  47. // .. chunk of prep code
  48. // execute task T
  49. // .. chunk of cleanup code
  50. }
  51. };
  52.  
  53. DoTask.do(task A)
  54. DoTask.do(task B)
  55. DoTask.do(task C)
  56.  
  57. //-- the target class
  58. class Resource {
  59. def open () { // sensitive operation }
  60. def close () { // sensitive operation }
  61. //-- target method
  62. def doWork() { println "working";} }
  63.  
  64. //-- the execute around code
  65. def static use (closure) {
  66. def res = new Resource();
  67. try {
  68. res.open();
  69. closure(res)
  70. } finally {
  71. res.close();
  72. }
  73. }
  74.  
  75. //-- using the code
  76. Resource.use { res -> res.doWork(); }
Add Comment
Please, Sign In to add comment