package iterator;
public interface Aggregate {
public abstract Iterator iterator();
}
Iterator.java
package iterator;
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
Order.java
package iterator;
import java.util.Date;
public class Order {
private String name;
private Date createdOn = new Date();
private Date updatedOn = new Date();
public Order(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
}
Orders.java
package iterator;
import java.util.Date;
public class Orders implements Aggregate{
private Order[] orders;
private int last = 0;
public Orders(int max){
this.orders = new Order[max];
}
public Order getOrderAt(int index){
return this.orders[index];
}
public void appendOrder(Order order){
this.orders[last] = order;
this.last ++ ;
}
public int getLength(){
return orders.length;
}
public Iterator iterator() {
return new OrdersIterator(this);
}
}
OrdersIterator.java
package iterator;
public class OrdersIterator implements Iterator{
private Orders orders;
private int index;
public OrdersIterator(Orders orders) {
this.orders = orders;
this.index = 0;
}
public boolean hasNext(){
if(index < orders.getLength()){
return true;
}else{
return false;
}
}
public Order next(){
Order order = orders.getOrderAt(this.index);
this.index ++ ;
return order;
}
}
IteratorTest.java
package iterator;
public class IteratorTest {
public static void main(String[] args) {
Orders orders = new Orders(3);
orders.appendOrder(new Order("order1"));
orders.appendOrder(new Order("order2"));
orders.appendOrder(new Order("order3"));
Iterator iterator = orders.iterator();
while(iterator.hasNext()) {
Order order = (Order)iterator.next();
System.out.println(order.getName());
}
}
}
you may download the source code.
No comments:
Post a Comment