samples/delegatingwriter/src/org/apidesign/delegatingwriter/AltBufferedWriter.java
2 * To change this template, choose Tools | Templates
3 * and open the template in the editor.
6 package org.apidesign.delegatingwriter;
8 import java.io.BufferedWriter;
9 import java.io.IOException;
10 import java.io.Writer;
13 * This is a regular {@link BufferedWriter}, just its implementation
14 * of the append method can choose from three options. This allows us to
15 * simulate the potential pros and cons of various possible implementations.
17 * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
19 public class AltBufferedWriter extends BufferedWriter {
20 private final Writer out;
21 private final Behaviour behaviour;
23 public AltBufferedWriter(Writer out) {
24 // behave exactly like BufferedWriter in 1.5 behaves
25 this(out, Behaviour.DELEGATE_TO_SUPER);
27 public AltBufferedWriter(Writer out, Behaviour behaviour) {
30 this.behaviour = behaviour;
34 public Writer append(CharSequence csq) throws IOException {
36 case THROW_EXCEPTION: return appendThrowException(csq);
37 case DELEGATE_TO_SUPER: return appendDelegateToSuper(csq);
38 case DELEGATE_TO_OUT: return appendDelegateToUnderlaying(csq);
39 case DELEGATE_CONDITIONALLY: return appendDelegateConditionally(csq);
40 default: throw new IllegalStateException("Unknown" + behaviour);
44 public Writer appendThrowException(CharSequence csq) throws IOException {
45 /* in case of real code, this would be part of the regular append method BEGIN: writer.throw
46 public Writer append(CharSequence csq) throws IOException {
47 /* thrown an exception as this method is new and subclasses need to override it */
48 throw new UnsupportedOperationException();
52 public Writer appendDelegateToSuper(CharSequence csq) throws IOException {
53 // non-efficient variant of delegating via converting to String first
54 // and using one of methods that existed in 1.4
55 // BEGIN: writer.throw.client
59 write(csq.toString());
62 // END: writer.throw.client
65 public Writer appendDelegateToUnderlaying(CharSequence csq) throws IOException {
66 // BEGIN: writer.delegateout
67 // efficient, yet dangerous delegation skipping methods unknown to
68 // subclasses that used version 1.4
71 // END: writer.delegateout
74 private Writer appendDelegateConditionally(CharSequence csq) {
75 throw new UnsupportedOperationException("Not yet implemented");
78 public enum Behaviour {
79 THROW_EXCEPTION, DELEGATE_TO_SUPER, DELEGATE_TO_OUT, DELEGATE_CONDITIONALLY