2006-12-18

クロージャの代りに無名クラスを使った場合

元記事:

http://www.arclamp.jp/blog/archives/marulec2006_2.html

http://d.hatena.ne.jp/t_yano/20061216/1166296467

こんな感じですか?

public interface Executable <T> {
    void execute(T argument);
}

public class IterationExecutor<T> {
    private Collection<T> collection;
    public IterationExecutor(Collection<T> collection) {
        this.collection = collection;
    }
    public IterationExecutor(T[] array) {
        this.collection = new ArrayList<T>();
        Collections.addAll(this.collection, array);
    }
    public void each(Executable<T> e) {
        for(T element: collection) {
            e.execute(element);
        }
    }
}

public class IntegerBuffer {
    private int value = 0;   
    public IntegerBuffer(int value) {
        this.value = value;
    }
    public void add(int number) {
        this.value += number;
    }
    public int getValue() {
        return this.value;
    }
}

public class Sample {
    public static void main(String[] args) {
        final IntegerBuffer total = new IntegerBuffer(0);
        new IterationExecutor<Integer>(new Integer[]{1,2,3,4,5}).each(
            new Executable<Integer>(){
                public void execute(Integer it) {
                    total.add(it);
                }
            });
        System.out.println(total.getValue());
    }
}

importなどは省略しました。

Sample以外は再利用可能なので……いやどうだろう

トラックバック - http://anond.hatelabo.jp/20061218033554