栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java什么是“Execute Around”?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java什么是“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 itexecuteWithFile("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);

调用代码无需担心打开/清理的一面,它将由处理

executeWithFile

坦白说,这在Java中是很痛苦的,因为闭包是如此word,从Java 8 lambda表达式开始就可以像许多其他语言一样实现(例如

C#lambda
表达式或
Groovy
),并且这种特殊情况是从Java 7开始使用
try-with-resourcesand AutoClosable流
处理的。

尽管“分配和清理”是给出的典型示例,但还有许多其他可能的示例-事务处理,日志记录,以更多特权执行某些代码等。它基本上有点类似于模板方法模式,但没有继承。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/420270.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号