我听说过的这个“围绕着执行”的成语(或类似的)是什么?为什么我可以使用它,为什么我可能不想使用它?
发布于 2008-12-04 20:51:32
基本上,它是一种模式,在这种模式中,你编写一个方法来完成总是需要的事情,例如资源分配和清理,并让调用者传入“我们想要对资源做什么”。例如:
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
来处理。
坦率地说,这在Java语言中是痛苦的,因为闭包是如此冗长,从Java8开始,λ表达式可以像在许多其他语言中一样实现(例如,Groovy表达式,或者C# ),并且这种特殊情况从Java7开始就使用try-with-resources
和AutoClosable
流来处理。
虽然“分配和清理”是一个典型的例子,但还有很多其他可能的例子--事务处理、日志记录、使用更多特权执行一些代码等。它基本上有点像template method pattern,但没有继承。
发布于 2008-12-04 20:55:19
当你发现自己不得不做这样的事情时,就会用到执行周围的成语:
//... chunk of init/preparation code ...
task A
//... chunk of cleanup/finishing code ...
//... chunk of identical init/preparation code ...
task B
//... chunk of identical cleanup/finishing code ...
//... chunk of identical init/preparation code ...
task C
//... chunk of identical cleanup/finishing code ...
//... and so on.
为了避免重复“围绕”实际任务执行的所有这些冗余代码,您可以创建一个自动处理它的类:
//pseudo-code:
class DoTask()
{
do(task T)
{
// .. chunk of prep code
// execute task T
// .. chunk of cleanup code
}
};
DoTask.do(task A)
DoTask.do(task B)
DoTask.do(task C)
这个习惯用法将所有复杂的冗余代码移到一个地方,并使您的主程序更具可读性(和可维护性!)
看看this post中的C#示例,以及this article中的C++示例。
发布于 2008-12-04 20:55:16
Execute Around Method是将任意代码传递给方法的地方,该方法可以执行设置和/或销毁代码,并在两者之间执行您的代码。
Java不是我用来做这件事的语言。将闭包(或lambda表达式)作为参数传递会更时髦。尽管对象可以说是equivalent to closures。
在我看来,围绕方法执行有点像Inversion of Control (依赖注入),您可以在每次调用该方法时进行即席更改。
但它也可以被解释为控制耦合的一个例子(通过它的参数告诉一个方法要做什么,在本例中是字面上的)。
https://stackoverflow.com/questions/341971
复制相似问题