什么是“周围执行"?成语? [英] What is the "Execute Around" idiom?

查看:12
本文介绍了什么是“周围执行"?成语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过的这个周围执行"成语(或类似的)是什么?为什么我可以使用它,为什么我不想使用它?

What is this "Execute Around" idiom (or similar) I've been hearing about? Why might I use it, and why might I not want to use it?

推荐答案

基本上,它是您编写方法来执行始终需要的事情的模式,例如资源分配和清理,并让调用者传入我们想对资源做什么".例如:

Basically it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in "what we want to do with the resource". For example:

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);

调用代码不需要担心打开/清理端 - 它会由 executeWithFile 处理.

The calling code doesn't need to worry about the open/clean-up side - it will be taken care of by executeWithFile.

坦率地说,这在 Java 中很痛苦,因为闭包太冗长了,从 Java 8 开始,lambda 表达式可以像在许多其他语言(例如 C# lambda 表达式或 Groovy)中一样实现,而这种特殊情况自 Java 7 开始使用 try-with-resourcesAutoClosable 流.

This was frankly painful in Java because closures were so wordy, starting with Java 8 lambda expressions can be implemented like in many other languages (e.g. C# lambda expressions, or Groovy), and this special case is handled since Java 7 with try-with-resources and AutoClosable streams.

虽然分配和清理"是给出的典型例子,但还有很多其他可能的例子 - 事务处理、日志记录、执行一些具有更多权限的代码等.它基本上有点像 模板方法模式,但没有继承.

Although "allocate and clean-up" is the typical example given, there are plenty of other possible examples - transaction handling, logging, executing some code with more privileges etc. It's basically a bit like the template method pattern but without inheritance.

这篇关于什么是“周围执行"?成语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆