【发布时间】:2014-05-24 16:20:13
【问题描述】:
假设您想将某个 Document 导出到 File 中(以某种格式...比如说 XML)。
为此,我有 XmlExporter 类,问题是......将 Document 和 File 传递给此类的最佳方法是什么?
选项 1: 导出器是无状态的,所以如果我想导出不同的文档或导出到不同的文件中,我只需更改参数即可。缺点是我必须在每个方法中传递文件(或者更确切地说是 OutputStream)(在复杂文档的情况下可能会很多)
class XmlExporter {
public function export(Document document, File file) {
this.writeHeader(document.header, file);
this.writeSomeOtherStuff(document.somethingElse, file);
// and more ...
}
private function writeHeader(DocumentHeader header, File file) {
writeName(header.name, file); // passing file over and over again
}
}
选项 2: 源和目标都存储在实例中。如果我想更改文件,我必须创建一个新对象,但现在我不必担心传递所有必要的数据。
class XmlExporter {
private final Document document;
private final File file;
public XmlExporter(Document document, File file) {
this.document = document;
this.file = file;
}
public function export() {
this.writeHeader(this.document.header);
}
private function writeHeader(DocumentHeader header) {
this.writeName(header.name);
}
private function writeName(String name) {
// ...
}
}
选项 3: 两者结合
class DocumentExporter {
public static function exportToXml(Document document, File file) {
XmlExporter exporter = new XmlExporter(document, file);
exporter.export();
}
// the rest same as Option 2, probably with private constructor
}
基本上,从编写类的角度来看,第二个选择对我来说最有意义,因为我不需要传递目标文件/流;但是从实际使用它的角度来看,我觉得第一个选择会更有意义。如果我想将其导出到标准输出而不是文件,或者导出多个文档怎么办?
【问题讨论】:
-
我个人会选择第二个,因为对我来说它基本上类似于当前使用装饰器模式处理文件的方式,但我不会将此作为答案提交。在我看来,这三者之间的选择很大程度上取决于当时什么是合适的
-
如何使用流畅的表示法,new XmlExporter().document(d).file(f).export();如果你想写入多个文件,file() 方法可能依赖于一个集合。
标签: java oop design-patterns coding-style