samples/delegatingwriter/src/org/apidesign/delegatingwriter/ExBufferedWriter.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:53:02 +0200
changeset 60 bea28c7c6653
permissions -rw-r--r--
Converting the Writer delegation problem into real example
     1 /*
     2  * To change this template, choose Tools | Templates
     3  * and open the template in the editor.
     4  */
     5 
     6 package org.apidesign.delegatingwriter;
     7 
     8 import java.io.BufferedWriter;
     9 import java.io.IOException;
    10 import java.io.Writer;
    11 
    12 /**
    13  * This is a regular {@link BufferedWriter}, just it optimizes for
    14  * huge {@link CharSequence} objects set to its {@link #append} method.
    15  * Instead of converting them to string, which might required too much
    16  * temporary memory, it delegates it directly.
    17  * <p>
    18  * This class is <q>simulating</q> would would happen if JDK's BufferedWriter 
    19  * in revision 1.5
    20  * was designed to delegate its newly added <code>append</code> methods
    21  * instead of calling its already existing <code>write</code> ones.
    22  * 
    23  * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
    24  */
    25 public class ExBufferedWriter extends BufferedWriter {
    26     private final Writer out;
    27     
    28     public ExBufferedWriter(Writer out, int sz, boolean optimized) {
    29         super(out, sz);
    30         this.out = optimized ? out : null;
    31     }
    32     
    33     @Override
    34     public Writer append(CharSequence csq) throws IOException {
    35         if (out != null) {
    36             // efficient, yet dangerous delegation skipping methods known to 
    37             // subclasses that used version 1.4
    38             out.append(csq);
    39             return this;
    40         } else {
    41             // non-efficient variant of delegating via converting to String first 
    42             // and using one of methods that existed in 1.4
    43             if (csq == null) {
    44                 write("null");
    45             } else {
    46                 write(csq.toString());
    47             }
    48             return this;
    49         }
    50     }
    51 }