Skip to content

Instantly share code, notes, and snippets.

@gchiam
Created August 18, 2020 04:07
Show Gist options
  • Save gchiam/b1c908c0a4644ae37aeeefcf098eb389 to your computer and use it in GitHub Desktop.
Save gchiam/b1c908c0a4644ae37aeeefcf098eb389 to your computer and use it in GitHub Desktop.
Execute Around Method Pattern - Resource
/* Extracted from https://www.youtube.com/watch?v=xF0rupA848E */
class Resource {
public Resource() {
System.out.println("created...");
}
public Resource op1() {
System.out.println("op1...");
return this;
}
public Resource op2() {
System.out.println("op2...");
return this;
}
private void close() {
System.out.println("clean up external resource");
}
public static void use(Consumer<Resource> block) {
Resource resource = new Resource();
try {
block.accept(resource);
} finally {
resource.close();
}
}
}
public class Sample {
public static void main(String[] args) {
Resource.use(resource ->
resource.op1()
.op2());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment