Design mode-iterative mode (iterator pattern) Java iterator (iterator) detailed explanation

Source: Internet
Author: User

The iterative pattern (iterator pattern) Java iterator (iterator) explains in detail


This address: Http://blog.csdn.net/caroline_wendy


Reference iterator pattern (iterator pattern): http://blog.csdn.net/caroline_wendy/article/details/35254643


The Java Standard library (util) includes an iterator interface (iterator interface), an import java.util.Iterator;

The inheritance (implements) iterator interface (Iterator) needs to override (override) Three functions: Hasnext (), Next (), and remove ();

The aggregation types of Java, such as ArrayList , include iterators.

However, the array type requires rewriting the corresponding iterator (iterator).


Detailed method:

1. The ArrayList type , including the iterator method, can be returned directly.

/** * @time June 20, 2014 */package iterator;import java.util.arraylist;import java.util.iterator;/** * @author C.L.Wang * * *  public class Pancakehousemenu implements Menu {arraylist<menuitem> menuitems;/** * */public pancakehousemenu () {// TODO auto-generated Constructor stubmenuitems = new arraylist<menuitem> (); AddItem ("K&b ' pancake Breakfast", "Pancakes with scrambled eggs, and toasts", true, 2.99); AddItem ("Regular Pancake Breakfast", "pancakes with fried eggs, sau Sage ", false, 2.99); AddItem (" Blueberry pancakes "," pancakes made with fresh blueberries ", true, 3.49); AddItem (" Waffles ", "Waffles, with your choice of blueberries or strawberries", true, 3.59);} public void AddItem (string name, String Description,boolean Vegetarian, double price) {MenuItem MenuItem = new MenuItem (NA Me, description, vegetarian, price); Menuitems.add (MenuItem);} Public iterator<menuitem> Createiterator () {return menuitems.iterator ();}}

2. array type , create the corresponding iterator class , inherit (implements) iterator (Iterator), override the Iterator method .

/** * @time June 26, 2014 */package iterator;import java.util.iterator;/** * @author C.l.wang * */public class Dinermenu Impl Ements Menu {static final int max_items = 6;int Numberofitems = 0; menuitem[] menuitems;/** * */public dinermenu () {//TODO auto-generated constructor stubmenuitems = new Menuitem[max_item S];additem ("Vegetarian BLT", "(Fakin ') Bacon with lettuce & tomato on whole Wheat", true, 2.99); AddItem ("BLT", "Bacon with lettuce & tomato in the whole wheat ", false, 2.99); AddItem (" Soup of the Day "," Soup of the Day ", with a side of PO Tato Salad ", false, 3.29); AddItem (" Hotdog "," A hot dog, with saurkraut, relish, onions, topped with cheese ", false, 3.05); }public void AddItem (string name, String Description,boolean Vegetarian, double price) {MenuItem MenuItem = new MenuItem (n Ame, description, vegetarian, price); if (Numberofitems >= max_items) {System.err.println ("Sorry, menu is full! Can ' t Add item to Menu ");} else {Menuitems[numberofitems] = Menuitem;++numberofitems;}} PUblic iterator<menuitem> Createiterator () {return new dinermenuiterator (MenuItems);}} /** * @time June 27, 2014 */package iterator;import java.util.iterator;/** * @author C.l.wang * */public class Dinermenuitera Tor implements iterator<menuitem> {menuitem[] items;int position = 0;/** * */public dinermenuiterator (menuitem[] It EMS) {//TODO auto-generated constructor stubthis.items = items;} /* (non-javadoc) * @see iterator.  Iterator#hasnext () */@Overridepublic Boolean hasnext () {//TODO auto-generated method stubif (position >= items.length || Items[position] = = null) {return false;} return true;} /* (non-javadoc) * @see iterator. Iterator#next () */@Overridepublic MenuItem Next () {//TODO auto-generated method Stubmenuitem MenuItem = items[position]; ++position;return MenuItem;} @Overridepublic void Remove () {if (position <= 0) {throw new IllegalStateException ("You can ' t remove a item until you ' ve done at least one next () ");} if (items[position-1]! = null) {for (int i=position-1; i< (items.length-1); ++i) {Items[i] = items[i+1];} ITEMS[ITEMS.LENGTH-1] = null;}}}

3. Menu Interface (interface), including methods for creating Iterators (Createiterator) .

/** * @time June 27, 2014 */package iterator;import java.util.iterator;/** * @author C.l.wang * */public interface Menu {Publ IC iterator<menuitem> createiterator ();}

4. Detailed menu items, arraylist and the basic elements of the array.

/** * @time June 20, 2014 */package iterator;/** * @author C.l.wang * */public class MenuItem {String name; String Description;boolean Vegetarian; is vegetarian double price;/** *  */public MenuItem (string name, string description, Boolean vegetarian, double price) {//TOD O auto-generated Constructor stubthis.name = name;this.description = Description;this.vegetarian = vegetarian; This.price = Price;} Public String GetName () {return name;} Public String GetDescription () {return description;} Public double GetPrice () {return price;} public Boolean Isvegetarian () {return vegetarian;}}

5. Customer Class (client), call iterator (iterator) method.

/** * @time June 27, 2014 */package iterator;import java.util.iterator;/** * @author C.l.wang * */public class Waitress {Menu Pancakehousemenu; Menu dinermenu;/** * */public Waitress (menu pancakehousemenu, menu dinermenu) {//TODO auto-generated constructor Stubthi S.pancakehousemenu = Pancakehousemenu;this.dinermenu = Dinermenu;} public void Printmenu () {iterator<menuitem> pancakeiterator = Pancakehousemenu.createiterator ();Iterator< menuitem> dineriterator = Dinermenu.createiterator (); System.out.println ("menu\n----\nbreakfast");p Rintmenu (pancakeiterator); System.out.println ("\nlunch");p Rintmenu (dineriterator);} private void Printmenu (Iterator<menuitem> Iterator) {while (Iterator.hasnext ()) {MenuItem MenuItem = (MenuItem) Iterator.next (); System.out.print (Menuitem.getname () + ":"); System.out.print (Menuitem.getprice () + "--"); System.out.println (Menuitem.getdescription ());}}}

6. Test:

/** * @time June 27, 2014 */package iterator;/** * @author C.l.wang * */public class Menutestdrive {/** * @param args */publi c static void Main (string[] args) {//TODO auto-generated method Stubpancakehousemenu Pancakehousemenu = new Pancakehousem ENU ();D inermenu dinermenu = new Dinermenu (); Waitress waitress = new Waitress (Pancakehousemenu, Dinermenu); Waitress.printmenu ();}}

7. Output:

MENU----breakfastk&b ' s pancake breakfast:2.99--pancakes with scrambled eggs, and toastregular pancake Breakfast:2. Pancakes with fried eggs, sausageblueberry pancakes:3.49 – pancakes made with fresh blueberrieswaffles:3.59--Wa Ffles, with your choice of blueberries or Strawberrieslunchvegetarian blt:2.99 – (Fakin ') Bacon with lettuce & Tomat O on whole wheatblt:2.99 – Bacon with lettuce & tomato on the whole wheatsoup of the day:3.29 – Soup of the day, W ith a side of potato saladhotdog:3.05--a hot dog, with saurkraut, relish, onions, topped with cheese









Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Design mode-iterative mode (iterator pattern) Java iterator (iterator) detailed explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.