As the purpose of buffer is to "buffer", let's modify our example to delegate to appendable methods directly only if the appendable is too big
3 import java.io.BufferedWriter;
4 import java.io.IOException;
6 /** Fixing the problem caused by mixing subclassing and delegation in
7 * the <code>java.io.BufferedWriter</code>
9 * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
11 public final class Writer implements Appendable {
12 private final Impl impl;
13 private final ImplSeq seq;
15 private Writer(Impl impl, ImplSeq seq) {
19 public final void write(int c) throws IOException {
21 char[] arr = {(char) c};
22 impl.write(arr, 0, 1);
24 seq.write(new CharSeq(c));
28 public final void write(char cbuf[]) throws IOException {
30 impl.write(cbuf, 0, cbuf.length);
32 seq.write(new CharSeq(cbuf, 0, cbuf.length));
35 public final void write(char cbuf[], int off, int len) throws IOException {
37 impl.write(cbuf, off, len);
39 seq.write(new CharSeq(cbuf, off, len));
42 public final void write(String str) throws IOException {
44 impl.write(str, 0, str.length());
49 public final void write(String str, int off, int len) throws IOException {
51 impl.write(str, off, len);
53 seq.write(str.subSequence(off, off + len));
57 public final void flush() throws IOException {
64 public final void close() throws IOException {
74 public final Writer append(CharSequence csq) throws IOException {
76 String s = csq == null ? "null" : csq.toString();
77 impl.write(s, 0, s.length());
84 public final Writer append(CharSequence csq, int start, int end) throws IOException {
85 return append(csq.subSequence(start, end));
88 public final Writer append(char c) throws IOException {
93 public static Writer create(Impl impl) {
94 return new Writer(impl, null);
97 public static Writer create(ImplSeq impl) {
98 return new Writer(null, impl);
101 public static Writer create(final java.io.Writer w) {
102 return new Writer(null, new ImplSeq() {
103 public void write(CharSequence seq) throws IOException {
107 public void close() throws IOException {
111 public void flush() throws IOException {
117 public static Writer createBuffered(final Writer out) {
118 return create(new SimpleBuffer(out));
122 public static interface Impl {
123 public void close() throws IOException;
124 public void flush() throws IOException;
125 public void write(String str, int off, int len) throws IOException;
126 public void write(char[] arr, int off, int len) throws IOException;
128 public static interface ImplSeq {
129 public void close() throws IOException;
130 public void flush() throws IOException;
131 public void write(CharSequence seq) throws IOException;