【发布时间】:2012-02-12 08:26:57
【问题描述】:
基于我原来的question about RSA and Base64 encoding 和那里的 cmets,我想知道编写 Base64OutputStream(或输入流)的最佳方法是什么。我最初将其称为 Base64PrintWriter 并将其从 PrintWriter 扩展为将 PrintWriter 传递给构造函数。
import org.bouncycastle.util.encoders.Base64;
public class Base64OutputStream extends FilterOutputStream {
public Base64OutputStream(OutputStream out) {
super(out);
}
public void write(byte[] decodedBytes) throws IOException {
byte[] base64Message = Base64.encode(decodedBytes);
super.write(base64Message);
}
public void writeln(byte[] decodedBytes) throws IOException {
write(decodedBytes);
super.write("\n".getBytes());
super.flush();
}
}
我将原来的实现更改为上面的实现,并使用以下命令对其进行初始化:
Base64OutputStream base64encoder = new Base64OutputStream(socket.getOutputStream());
我的问题是:
- 这是一个好的设计吗?
- 还能做得更好吗?
- 我是否正确应用了装饰器模式。
- 扩展FilteredOutputStream而不是OutputStream好不好? Oracle 表示它很好,但是仍然从 OutputStream 扩展有什么缺点或理由吗?
- 当我调用构造函数时,我是否应该额外用 BufferedOutputStream 装饰它?
【问题讨论】:
-
嗨 lanoxx,您让我对您其他问题中的设计发表评论。正如我所说,我个人宁愿将 Writer 作为父级(对于编码器),因为它使字符编码错误更难发生(例如,在写入包含 UTF-16 字符的流时)。否则,我建议您查看 Brent Wordens 的答案并复制 Apache 界面(例如换行处理)。严重缺乏的一件事是正确的异常处理,您可能想要解决这个问题。如果您愿意,我可以粘贴 Java 1.5 或更高版本的基于状态的实现。