基于我原来的question about RSA and Base64 encoding和那里的评论我想知道编写 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 来装饰它?
最佳答案
如果您愿意使用开源,您可以查看Apache Commons Codec 。它包含 Base64OutputStream这应该可以满足您的需求。
关于Java,Base64 : How to write a Base64OutputStream class using Decorator Pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8896237/