首页 > 其他 > 详细

[编码模式]Execute Around

时间:2015-08-20 21:03:46      阅读:263      评论:0      收藏:0      [点我收藏+]

背景

很多时候,我们访问资源需要关注对资源的锁定、对资源的申请和释放,还有考虑可能遇到的各种异常。这些事项本身与代码的逻辑操作无关,但我们不能遗漏。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);


[编码模式]Execute Around

原文:http://my.oschina.net/sulliy/blog/495240

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!