JAVA-based design pattern of the iterator pattern

  • Introduction

    Iterative mode and accessed by a sequential polymerization in the content object, regardless of the internal representation of the aggregate object. That is, through an interface through all the contents of the parties object, regardless of the underlying implementation, is a linked list or array; a delete () or remove () and so on.

    Container roles: the definition of a standard interface, List, Set.

    DETAILED container role: specific underlying implementation, LinkedList list specific implementation, ArrayList array implementation. # Sample Code to implement the array, and the built-in element is a custom object, and therefore the generic reflection underlying implementation

    Iterator role: next (), hasNext ()

    Specific iterator role

  • Class Diagram

  

  • Code

 

public interface Iterator<T>{
    public T Next();
    public boolean hasNext();
}

public class ConcreteIterator<T> implements Iterator<T> {
    private Aggregate<T>list;
    private int index;
    public ConcreteIterator(Aggregate<T>list){
        this.list=list;
        index=0;
    }
    public T Next() {
        return list.get(index++);
    }

    public boolean hasNext() {
        if(index>=list.size()){
            return false;
        }else{
            return true;
        }
    }
}

public interface Aggregate<T> {
    public void add(T object);
    public T get(int index);
    public Iterator<T>iterator();
    public int size();
}

import java.lang.reflect.Array;

public class ConcreteAggregate<T>implements Aggregate<T> {
    private T[] list;
    private int size=0;
    private int index=0;
    public ConcreteAggregate(Class<T> type, int size){
        list=(T[]) Array.newInstance(type,size);
    }
    public void add(T object) {
        list[index++]=object;
        size++;
    }

    public T get(int index) {
        return list[index];
    }

    public Iterator<T> iterator() {
        return new ConcreteIterator<T>(this);
    }

    public int size() {
        return size;
    }
}

public class Main {
    public static void main(String[] args) {
        Aggregate<Item>television=
                new ConcreteAggregate<Item>(Item.class,10);
        television.add(new Item("CCTV1"));
        television.add(new Item("天津卫视"));
        television.add(new Item("金鹰卡通"));
        television.add(new Item("卡酷动画"));
        Iterator<Item>iterator=television.iterator();
        while(iterator.hasNext()){
            Item item=iterator.Next();
            System.out.println(item.getName());
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/hbsdljz/p/11128759.html