Iterator pattern of design pattern

Iterator mode

definition
Provides a method to sequentially access the elements of an aggregate object without exposing the internal representation of the object.
In short, different types of objects may require different traversal methods. We assign an iterator to each type of object, and finally combine multiple iterators into one
Main solution
Different ways to traverse the entire integration object
When to use
Traverse an aggregate object
How to solve
The responsibility for moving between elements is left to the iterator, not to the aggregate object
critical code
Interface definition: hasNext, next
Expected instance
iterator in JAVA
advantage
1. It supports traversing an aggregate object in different ways
2. Iterators simplify aggregate classes
3. There can be multiple traversals on the same aggregate
4. In iterator mode, it is convenient to add new aggregate classes and iterators without modifying the source code
shortcoming
Because the iterator pattern separates the responsibility of storing data and traversing data, adding a new aggregation class needs to add a new iterator class, and the number of classes increases in pairs, which increases the complexity of the system to a certain extent.

Pattern structure and code examples

(1) Iterator role: defines the method required to traverse the element. Generally speaking, there are three methods: get the method next() of the next element, judge whether to traverse the end method hasNext(), and move out the method remove() of the current object
(2) Concrete Iterator role: implement the methods defined in the iterator interface to complete the iteration of the collection
(3) Container role (Aggregate): it is generally an interface that provides an iterato() method, such as the collection interface, List interface, Set interface, etc. in java
(4) Concrete aggregate: it is the concrete implementation class of the abstract container, such as ArrayList for the ordered List of the List interface, LinkList for the linked List of the List interface, HashSet for the Hash List of the Set interface, etc

For example (the coffee shop and Chinese restaurant are merged. The menus of the two restaurants are saved in array and ArrayList. The traversal methods are different. Only one method is needed for aggregation access using iterators)

1. Iterator interface

public interface Iterator {
	
	public boolean hasNext();
	public Object next();
	
}

2. Coffee shop menu and coffee shop menu traverser

public class CakeHouseMenu {
    private ArrayList<MenuItem> menuItems;

    public CakeHouseMenu() {
        menuItems = new ArrayList<MenuItem>();

        addItem("KFC Cake Breakfast","boiled eggs&toast&cabbage",true,3.99f);
        addItem("MDL Cake Breakfast","fried eggs&toast",false,3.59f);
        addItem("Stawberry Cake","fresh stawberry",true,3.29f);
        addItem("Regular Cake Breakfast","toast&sausage",true,2.59f);
    }

    private void addItem(String name, String description, boolean vegetable, float price) {
        MenuItem menuItem = new MenuItem(name,description,vegetable,price);
        menuItems.add(menuItem);
    }

    public Iterable getIterator()
    {
        return new CakeHouseIterator();
    }
    
    class CakeHouseIterator implements Iterable
    {
        private int position=0;
        public CakeHouseIterator()
        {
            position=0;
        }
        
        @Override
        public boolean hasNext() {
            // TODD Auto-generated method stub
            if(position< menuItems.size())
            {
                return true;
            }
            return false;
        }
        
        @Override
        public object next() {
            // TODD Auto-generated method stub
            MenuItem menuItem = menuItems.get(position);
            position++;
            return menuItem;
        }
    };
}

3. Chinese restaurant menu and Chinese restaurant menu traverser

public class DinerMenu {
    private final static int Max_Items = 5;
    private int numberOfItens = 0;
    private MenuItem[] menuItems;

    public DinerMenu() {
        menuItems = new MenuItem[Max_Items];
        addItem("vegetable Blt", "bacon&lettuce&tomato&cabbage", true, 3.58f);
        addItem("Blt", "bacon&lettuce&tomato", false, 3.00f);
        addItem("bean soup", "bean&potato salad", true, 3.28f);
        addItem("hotdog", "onions&cheese&bread", false, 3.05f);
    }

    private void addItem(String name, String description, boolean vegetable, float price){
        MenuItem menuItem = new MenuItem(name,description,vegetable,price);
        if(numberOfItens >= Max_Items) {
            System.out.println("sorry,menu is full!can not add another  item");
        }else {
            menuItem[numberOfItens] = menuItem;
            numberOfItens++;
        }
    }

    public Iterable getIterator() {
        return new DinerIterator();
    }
    
    class DinerIterator implements Iterable {
        private int position;
        
        public DinerIterator() {
            position = 0;
        }
        
        @Override
        public boolean hasNext() {
            // TODD Auto-generated method stub
            if (position < numberOfItens) {
                return  true;
            }
            return  false;
        }
        
        @Override
        public Objects next() {
            //TODO Auto-generated method stub
            MenuItem menuItem = menuItems[position];
            position++;
            return menuItem;
        }
    }
}

4. Waitress

public class Waitress {
	private ArrayList<Iterator> iterators = new ArrayList<Iterator>();
 
	public Waitress() {
 
	}
 
	public void addIterator(Iterator iterator) {
		iterators.add(iterator);
 
	}
 
	public void printMenu() {
		Iterator iterator;
		MenuItem menuItem;
		for (int i = 0, len = iterators.size(); i < len; i++) {
			iterator = iterators.get(i);
 
			while (iterator.hasNext()) {
				menuItem = (MenuItem) iterator.next();
				System.out
						.println(menuItem.getName() + "***" + menuItem.getPrice() + "***" + menuItem.getDescription());
 
			}
 
		}
 
	}
 
	public void printBreakfastMenu() {
 
	}
 
	public void printLunchMenu() {
 
	}
 
	public void printVegetableMenu() {
 
	}
}

Tags: Java

Posted on Wed, 20 Oct 2021 15:55:16 -0400 by ajar