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