在写代码的时候,常常会遇到这样的情况:每次在执行一段代码的时候,都需要先执行一些代码;执行完之后,再执行另一些代码。比如在读写文件的时候,我们真正care的逻辑是"读写",至于文件流的初始化、打开、关闭、异常处理等都不是我们关心的。但是,每次在"读写"之前,我们需要执行打开操作,"读写"之后,需要执行关闭操作。这个时候就可以使用"execute around 模式"来提炼出"读写"前后的公共代码,从而把心思放在"读写"的逻辑上。
类图:
代码:
/**
*
* Interface for specifying what to do with the file resource.
*
*/
public interface FileWriterAction {
void writeFile(FileWriter writer) throws IOException;
}
/**
*
* SimpleFileWriter handles opening and closing file for the user. The user only has to specify what
* to do with the file resource through {@link FileWriterAction} parameter.
*
*/
public class SimpleFileWriter {
/**
* Constructor
*/
public SimpleFileWriter(String filename, FileWriterAction action) throws IOException {
FileWriter writer = new FileWriter(filename); // 读写前的操作
try {
action.writeFile(writer); // 读写
} finally {
writer.close(); // 读写后的操作
}
}
}
/**
* The Execute Around idiom specifies some code to be executed before and after a method. Typically
* the idiom is used when the API has methods to be executed in pairs, such as resource
* allocation/deallocation or lock acquisition/release.
* <p>
* In this example, we have {@link SimpleFileWriter} class that opens and closes the file for the
* user. The user specifies only what to do with the file by providing the {@link FileWriterAction}
* implementation.
*
*/
public class App {
/**
* Program entry point
*/
public static void main(String[] args) throws IOException {
new SimpleFileWriter("testfile.txt", new FileWriterAction() {
@Override
public void writeFile(FileWriter writer) throws IOException {
// 真正关心的"读写"逻辑
writer.write("Hello");
writer.append(" ");
writer.append("there!");
}
});
}
}