Advertisement
JustCaused

SP - Iterator Pattern

Dec 8th, 2022
777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. package ZITR1;
  2. // Задатак RZITR1: Додати програм на месту три тачке како би се добила порука:
  3. // Items:
  4. // 4
  5. // 2
  6. // 1
  7. // 5
  8. // 3
  9.  
  10. class Client {
  11.     Aggregate ag;
  12.     Iterator it;
  13.    
  14.     Client(){
  15.         ag=new ConcreteAggregate();
  16.          it = new ConcreteIterator((ConcreteAggregate) ag);
  17.      }
  18.    
  19.     public static void main(String args[]) {
  20.         Client cl = new Client();  
  21.         cl.printItems();
  22.     }
  23.     void printItems() {
  24.         System.out.println("Items:");
  25.         it.First();
  26.         while (it.IsEnd()) {
  27.             System.out.println(it.currentItem());
  28.             it.Next();
  29.         }
  30.   }}
  31.  
  32. abstract class  Aggregate{
  33.     int n[];
  34.    
  35.     abstract Iterator createIterator();
  36.     int getItem(int indeks) {return n[indeks];}
  37.     int getItemsNumber(){return n.length;}
  38. }
  39.  
  40. class ConcreteAggregate extends Aggregate   {
  41.     ConcreteAggregate() { n = new int[5]; n[0]=4; n[1]=2; n[2]=1; n[3]=5; n[4]=3;}
  42.    
  43.     Iterator createIterator() { return new ConcreteIterator(this);}
  44. }
  45.  
  46. abstract class Iterator{
  47.     abstract void First();
  48.     abstract void Next();
  49.     abstract boolean IsEnd();
  50.     abstract int currentItem();
  51. }
  52.  
  53. class ConcreteIterator extends Iterator  {
  54.   ConcreteAggregate ag;
  55.   int indeks;
  56.  
  57.   ConcreteIterator(ConcreteAggregate ag1) {ag = ag1;}
  58.  
  59.   void First() {indeks = 0;}
  60.   void Next() {indeks++;}
  61.   boolean IsEnd () {return indeks < ag.getItemsNumber();}
  62.   int currentItem() {return ag.getItem(indeks);}  
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement