<< S2JDBC | Home | ピアノソナタ16番 >>
PR: 転職    お墓    エコ    通販    結婚相談所    シルバー    質屋    葬式    漫画    エステサロン   

流れるようなインターフェース

最近は、StringBuffer.append()みたいなのも、流れるようなインターフェースなのか。まぁ本質的に違いはないわけだけど。自分がコンテナクラスのインスタンスを手軽に造りたい時に使っているのは、こんなの。

public class CollectionBuilder {
    private Collection collection;
    public CollectionBuilder(Collection collection) {
        if (collection == null) throw new NullPointerException("collection is null.");
        this.collection = collection;
    }
    public CollectionBuilder add(Object o) {
        if (collection == null) throw new IllegalStateException("Create new CollectionBuilder.");
        collection.add(o);
        return this;
    }
    public Collection get() {
        if (collection == null) throw new IllegalStateException("Create new CollectionBuilder.");
        Collection ret = collection;
        collection = null;
        return ret;
    }
    public Collection getUnmodifiable() {
        return Collections.unmodifiableCollection(get());
    }
}
public class TypedCollectionBuilder<T> {
    private CollectionBuilder builder;
    public TypedCollectionBuilder(Collection<T> collection) {
        builder = new CollectionBuilder(collection);
    }
    public TypedCollectionBuilder<T> add(T o) {
        builder.add(o);
        return this;
    }
    @SuppressWarnings("unchecked")
    public Collection<T> get() {
        return (Collection<T>)builder.get();
    }
    @SuppressWarnings("unchecked")
    public Collection<T> getUnmodifiable() {
        return (Collection<T>)builder.getUnmodifiable();
    }
}
Collection<String> c = new TypedCollectionBuilder<String>(new LinkedList<String>())
    .add("Hello")
    .add("World")
    .getUnmodifiable();



コメント追加 トラックバック送信
このサイトの掲載内容は私自身の見解であり、必ずしもIBMの立場、戦略、意見を代表するものではありません。
日本アイ・ビー・エム 花井 志生 Since 1997.6.8