author | Jaroslav Tulach <jaroslav.tulach@apidesign.org> |
Thu, 30 Oct 2014 20:46:27 +0100 | |
changeset 408 | 9a439a79c6d0 |
permissions | -rw-r--r-- |
jtulach@151 | 1 |
package org.apidesign.samples; |
jtulach@151 | 2 |
|
jtulach@151 | 3 |
import java.util.ArrayList; |
jtulach@151 | 4 |
import java.util.List; |
jtulach@151 | 5 |
|
jtulach@151 | 6 |
public class StringBuffer { |
jtulach@151 | 7 |
private List<String> all = new ArrayList<String>(); |
jtulach@151 | 8 |
|
jtulach@151 | 9 |
public StringBuffer() { |
jtulach@151 | 10 |
// prevent subclassing from 3rd party code |
jtulach@151 | 11 |
if (getClass() != StringBuffer.class && getClass() != StringBufferUnsynch.class) { |
jtulach@151 | 12 |
throw new IllegalStateException(); |
jtulach@151 | 13 |
} |
jtulach@151 | 14 |
} |
jtulach@151 | 15 |
|
jtulach@151 | 16 |
// BEGIN: string.buffer.factory |
jtulach@151 | 17 |
public static StringBuffer createUnsynchronized() { |
jtulach@151 | 18 |
return new StringBufferUnsynch(); |
jtulach@151 | 19 |
} |
jtulach@151 | 20 |
// END: string.buffer.factory |
jtulach@151 | 21 |
|
jtulach@151 | 22 |
public synchronized StringBuffer append(String s) { |
jtulach@151 | 23 |
return appendImpl(s); |
jtulach@151 | 24 |
} |
jtulach@151 | 25 |
|
jtulach@151 | 26 |
@Override |
jtulach@151 | 27 |
public synchronized String toString() { |
jtulach@151 | 28 |
return toStringImpl(); |
jtulach@151 | 29 |
} |
jtulach@151 | 30 |
|
jtulach@151 | 31 |
final String toStringImpl() { |
jtulach@151 | 32 |
String ret = ""; |
jtulach@151 | 33 |
for (String s : all) { |
jtulach@151 | 34 |
ret += s; |
jtulach@151 | 35 |
} |
jtulach@151 | 36 |
return ret; |
jtulach@151 | 37 |
} |
jtulach@151 | 38 |
|
jtulach@151 | 39 |
|
jtulach@151 | 40 |
final StringBuffer appendImpl(String s) { |
jtulach@151 | 41 |
all.add(s); |
jtulach@151 | 42 |
return this; |
jtulach@151 | 43 |
} |
jtulach@151 | 44 |
|
jtulach@151 | 45 |
|
jtulach@151 | 46 |
private static final class StringBufferUnsynch extends StringBuffer { |
jtulach@151 | 47 |
@Override |
jtulach@151 | 48 |
public StringBuffer append(String s) { |
jtulach@151 | 49 |
return appendImpl(s); |
jtulach@151 | 50 |
} |
jtulach@151 | 51 |
@Override |
jtulach@151 | 52 |
public String toString() { |
jtulach@151 | 53 |
return toStringImpl(); |
jtulach@151 | 54 |
} |
jtulach@151 | 55 |
} |
jtulach@151 | 56 |
} |