「DesignPattern/IteratorPattern/JavaCode1」の編集履歴(バックアップ)一覧に戻る

DesignPattern/IteratorPattern/JavaCode1 - (2008/09/09 (火) 19:45:06) のソース

//java/linenumber


package sample.design_pattern;

interface Iterator {
    public abstract boolean hasNext();
    public abstract void next();

    public abstract Object getValue();
}



interface Aggregate {
    public abstract Iterator iterator();
}



class Element {
    private int value;

    public Element(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}



class ElementIterator implements Iterator {
    private ElementList list;
    private int index;

    public ElementIterator(ElementList list) {
        this.list = list;
        this.index = 0;
    }

    public boolean hasNext() {
        return (list.getLastNum() > index) ? true : false;
    }

    public void next() {
        ++index;
    }

    public Object getValue() {
        return list.getValueAt(index);
    }
}



class ElementList implements Aggregate {
    private Element[] list;
    private int last = 0;

    public ElementList(int count) {
        this.list = new Element[count];
    }

    public void add(Element element) {
        list[last++] = element;
    }

    public Element getValueAt(int index) {
        return list[index];
    }

    public int getLastNum() {
        return last;
    }

    public Iterator iterator() {
        return new ElementIterator(this);
    }
}



public class IteratorPatternTest {
    public static void main(String[] args) {
        ElementList list = new ElementList(5);

        for (int i = 0; i < 5; ++i) {
            list.add(new Element(i));
        }

        for (Iterator it = list.iterator(); it.hasNext(); it.next()) {
            System.out.println(((Element)it.getValue()).getValue());
        }
    }
}