Design pattern(iterator)

Iterator — поведенческий шаблон проектирования. Представляет собой объект, позволяющий получить последовательный доступ к элементам объекта-агрегата без использования описаний каждого из агрегированных объектов.
Create interfaces.
Iterator.java
public interface Iterator {
   public boolean hasNext();
   public Object next();
}
Container.java
public interface Container {
   public Iterator getIterator();
}

Step 2

Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface.
NameRepository.java
public class NameRepository implements Container {
   public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};

   @Override
   public Iterator getIterator() {
      return new NameIterator();
   }

   private class NameIterator implements Iterator {

      int index;

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

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

Step 3

Use the NameRepository to get iterator and print names.
IteratorPatternDemo.java
public class IteratorPatternDemo {
 
   public static void main(String[] args) {
      NameRepository namesRepository = new NameRepository();

      for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
         String name = (String)iter.next();
         System.out.println("Name : " + name);
      }  
   }
}

Step 4

Verify the output.
Name : Robert
Name : John
Name : Julie
Name : Lora

1 комментарий:

  1. Casino Finder - Las Vegas (NV) - Mapyro
    Find 포천 출장샵 Casino Finder, 울산광역 출장안마 Las Vegas (NV) location offering 양주 출장마사지 street parking, street parking, Near 영천 출장샵 the Casino and Hotel. 3131 South Las 이천 출장마사지 Vegas Blvd.

    ОтветитьУдалить