Iterator Pattern

wangjh789·2022년 8월 31일
0

Design Pattern

목록 보기
8/13
public interface Iterator {

    boolean hasNext();

    Object next();
}

public class NameIterator implements Iterator{

    private String[] names;
    private int index;

    public NameIterator(String[] names) {
        this.names = names;
    }

    @Override
    public boolean hasNext() {
        return index < this.names.length;
    }

    @Override
    public Object next() {
        if (hasNext()) {
            return this.names[index++];
        }
        return null;
    }
}

public class NameRepository {
    private String[] names =  {"A","B","C"};

    public Iterator getIterator() {
        return new NameIterator(names);
    }
}
    public static void main(String[] args) {
        NameRepository repository = new NameRepository();

        for (Iterator iter = repository.getIterator(); iter.hasNext();) {
            String name = (String) iter.next();
            System.out.println(name);

        }
    }
profile
기록

1개의 댓글

comment-user-thumbnail
2022년 10월 12일

cex

답글 달기
Powered by GraphCDN, the GraphQL CDN