一个好的做法是在 close 方法(AutoCloseable 接口)中包含业务逻辑,而不是手动调用逻辑,而是通过 try-with-resource ?
我有一个场景,我使用 jax-b 将流方式写入 XML 文件,我需要手动编写开始标记元素和开始结束元素。业务逻辑很接近,但我认为这不是好的做法,你的意见是什么?
我的例子
public class PhoneBookWriter implements AutoCloseable {
public void open(Path filePath) {
// open file
}
public void write(PhoneBookInfo phoneBookInfo) {
// write phone book pojo to xml file
}
public void close() {
// check if stream is not null
// --> part of business logic -> writeEndElement via XmlOutputWriterStream
// close stream
}
您对打开和关闭方法有何看法?方法可以有业务逻辑还是只有打开流(open 方法)和关闭流(close 方法)?是否应该将另一个逻辑提取到专用方法中?