Created
August 18, 2020 04:07
-
-
Save gchiam/b1c908c0a4644ae37aeeefcf098eb389 to your computer and use it in GitHub Desktop.
Execute Around Method Pattern - Resource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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