제2 5 편 디자인 모델 - 교체 기 모델

정의: 취 합 대상 의 각 요 소 를 순서대로 방문 하 는 방법 을 제공 하고 이 대상 의 내부 표 시 를 노출 하지 않 아 도 됩 니 다.
코드:
package iterator_model;

import java.util.ArrayList;
import java.util.List;
/**
 * 
 * @author naivor
 *		     -   
 */
public class IteratorModel {
	public static void main(String[] args) {
		List<Object> list=new ArrayList<Object>();
		list.add("hello");
		list.add("  ");
		list.add("  ");
		list.add("  ");
		list.add("  ");
		list.add("  ");
		
		ConcreteAggregate aggregate=new ConcreteAggregate(list);
		ConcreteIterator iterator=new ConcreteIterator(aggregate);
		
		Object item=iterator.first();
		while(!iterator.isDone()){
			item=iterator.currentItem();
			System.out.println(item.toString());
			
			iterator.next();
		}
	}
}
/**
 * 
 * @author naivor
 *		     -      
 */
abstract class Iterator{
	 public abstract Object first();
	 public abstract Object next();
	 public abstract boolean isDone();
	 public abstract Object currentItem();
}
/**
 * 
 * @author naivor
 *		     -     
 */
abstract class Aggregate{
	public abstract Iterator createIterator();
}
/**
 * 
 * @author naivor
 *		     -     
 */
class ConcreteAggregate extends Aggregate{
	private List<Object> items;
	
	public ConcreteAggregate(List<Object> items) {
		this.items=items;
	}
	@Override
	public Iterator createIterator() {
		// TODO Auto-generated method stub
		return new ConcreteIterator(this);
	}
	
	public int getCount(){
		return items.size();
	}
	
	public Object getItem(int index){
		return items.get(index);
	}
	
	
}
/**
 * 
 * @author naivor
 *		     -      
 */
class ConcreteIterator extends Iterator{
	private ConcreteAggregate aggregate;
	private int current=0;
	
	public ConcreteIterator(ConcreteAggregate aggregate) {
		this.aggregate=aggregate;
	}

	@Override
	public Object first() {
		return aggregate.getItem(0);
	}

	@Override
	public Object next() {
		current++;
		if (current<=aggregate.getCount()) {
			return aggregate.getItem(current);
		}
		return null;
	}

	@Override
	public boolean isDone() {
		if (current>=aggregate.getCount()) {
			return true;
		}
		return false;
	}

	@Override
	public Object currentItem() {
		return aggregate.getItem(current);
	}
	
}

좋은 웹페이지 즐겨찾기