背景
很多时候,我们访问资源需要关注对资源的锁定、对资源的申请和释放,还有考虑可能遇到的各种异常。这些事项本身与代码的逻辑操作无关,但我们不能遗漏。Execute Around可以帮助我们,只是需要使用者指出我想怎么使用资源就可以。不需要考虑锁、资源申请释放,或者异常,对码农是一种解放。
场景
Execute Around需要定义操作资源的接口,该接口提供使用者来提供具体的实现。模式提供一个执行接口,该接口的实现来对资源使用前的准备工作,以及资源使用后的清理工作。
实例
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 -> System.out.println(s.read()));
// Or with Java 8 Method reference:
executeWithFile("filename.txt", ClassName::methodName);
原文:http://my.oschina.net/sulliy/blog/495240