Design pattern Learning Path-iterator mode-encapsulation traversal

Source: Internet
Author: User

Take a look at the iterator pattern today.

When it comes to iterators, a bit of programming experience should know iterator. Yes, this is the iterator.

Sometimes in the process of taking a loop, we usually get the iterator in the container and loop through the iterator.

What is an iterator pattern? Provides a way to access each element of an aggregated object sequentially without exposing its internal representation.

Here's a little example to explain.

There are two restaurants to merge, one is Chinese restaurant, one is Hong Kong-style tea, because the merger, two things are sold, ordering people want to be able to point two different things at the same time.

But there is a problem, in their menu, although the menu details are the same, one is implemented with an array, one is implemented by the list (here is not to discuss the pros and cons of arrays and lists).

This is the menu details, including the name of the dish, description and price.

Package com.chris.iterator;

public class MenuItem {
	String name;
	String description;
	Double Price;

	Public MenuItem (string name, string description, double price) {
		this.name = name;
		this.description = description;
		This.price = Price;
	}

	Public String GetName () {return
		name;
	}

	Public String GetDescription () {return
		description;
	}

	Public double GetPrice () {return price
	}
}

The menu for Chinese restaurants is to use an array to save the items.

Package com.chris.iterator;

public class Chinesemenu {
	static final int max_items = ten;
	int numberofitems = 0;
	Menuitem[] MenuItems;
	
	Public Chinesemenu () {
		MenuItems = new Menuitem[max_items];
		AddItem ("Fish head with chopped chili Peppers", "Hunan cuisine, very delicious chopped chili fish Head",);
		AddItem ("cooked meat", "especially delicious",);
		AddItem ("dry pot cauliflower", "with a dry pot of cauliflower, very delicious",);
		AddItem ("Dongpo Meat", "Su Dongpo's meat.") ",);
	}
	
	public void AddItem (string name, string description, double price) {
		MenuItem MenuItem = new MenuItem (name, Descriptio n, price);
		if (Numberofitems >= max_items) {
			System.err.println ("Sorry, menu is full! Can ' t Add item to menu ');
		else{
			Menuitems[numberofitems] = MenuItem;
			numberofitems++ 
		}
	}
	
	Public menuitem[] Getmenuitems () {return
		MenuItems
	}}

And Hong Kong-style tea restaurant menu with a linked list to save the menu.

Package com.chris.iterator;

Import java.util.ArrayList;

public class Hongkongmenu {
	ArrayList MenuItems;
	
	Public Hongkongmenu () {
		MenuItems = new ArrayList ();
		AddItem ("Crystal shrimp dumplings", "There are shrimp, very delicious",);
		AddItem ("Steamed ribs with soy sauce", "to wait for some time, but very delicious",);
		AddItem ("Quicksand Bag", "Sweet, Super Delicious", ten);
		AddItem ("Barbecued pork bun", "Guangdong characteristics, good",);
	}
	
	public void AddItem (string name, string description, double price) {
		MenuItem MenuItem = new MenuItem (name, Descriptio n, price);
		Menuitems.add (MenuItem);
	}
	
	Public ArrayList Getmenuitems () {return
		MenuItems;
	}
}

There seems to be no problem, but each time the waiter presents the menu, he needs to create two menus and then get the menu inside.

Because the menu container is different, need to be shown separately through two loops, print out the situation of the menu (if you merge a restaurant, it will take three cycles.) )


Both sides of the menu are unwilling to change their implementation, possibly due to too many other associations (this is the case in actual development).

So we started thinking about other solutions, encapsulating the traversal.

All we need to do is encapsulate the changed parts, and that's the difference between the two container traversal methods and the way to get the elements.

The list is through. Size () and get (index), and the array is through. length and [index], which causes their loops to not be uniform.


We begin by introducing an iterator pattern, creating an iterator interface that is simply no longer simple, with only two methods to get the next element and determine if there is a next element.

Package com.chris.iterator;

Public interface Iterator {
	Boolean hasnext ();
	Object next ();


We do an iterator for the Chinese restaurant, for his menu services, to achieve the above interface two methods.

Package com.chris.iterator;

public class Chinesemenuiterator implements iterator{
	
	menuitem[] items;
	int position = 0;

	Public Chinesemenuiterator (menuitem[] items) {
		this.items = items;
	}
	
	@Override Public
	Boolean hasnext () {
		if (position >= items.length | | items[position] = NULL) {
			return false;
		} else{return
			true;
		}
	}

	@Override public
	Object Next () {
		MenuItem MenuItem = items[position];
		Position + +;
		Return MenuItem
	}

}

Similarly, the Hong Kong-style tea restaurant is also made an iterator for their menu services.

Package com.chris.iterator;

Import java.util.ArrayList;

public class Hongkongmenuiterator implements iterator {
	ArrayList MenuItems;
	int position = 0;

	Public Hongkongmenuiterator (ArrayList MenuItems) {
		this.menuitems = MenuItems;
	}

	@Override Public
	Boolean hasnext () {
		if (position >= menuitems.size () | | menuitems.get (POSITION) = null) {
  return false;
		else {return
			true;
		}
	}

	@Override public
	Object Next () {
		MenuItem MenuItem = (MenuItem) menuitems.get (position);
		position++;
		Return MenuItem
	}

}

Then in their menu, the way to get the menu to delete, add a method, return to their respective iterators, so OK.

Then, the waiter report the menu is more convenient, do not need a few cycles, only through a unified traversal of the elements of the cycle to print out, the code instantly become elegant.

Package com.chris.iterator;

public class Waitress {
	chinesemenu chinesemenu;
	Hongkongmenu Hongkongmenu;
	
	Public waitress (Chinesemenu Chinesemenu, Hongkongmenu hongkongmenu) {
		this.chinesemenu = Chinesemenu;
		This.hongkongmenu = Hongkongmenu;
	}
	
	public void Printmenu () {
		iterator chinesemenuiterator = Chinesemenu.createiterator ();
		Iterator Hongkongmenuiterator = Hongkongmenu.createiterator ();
		System.out.println ("Chinese Food:");
		Printmenu (chinesemenuiterator);
		SYSTEM.OUT.PRINTLN ("Hongkong Food:");
		Printmenu (Hongkongmenuiterator);
	}
	
	private void Printmenu (iterator iterator) {while
		(Iterator.hasnext ()) {
			MenuItem MenuItem = (MenuItem) Iterator.next ();
			System.out.print (Menuitem.getname () + "-");
			System.out.print (menuitem.getdescription () + "-");
			System.out.println (Menuitem.getprice ());}}


Test code is not posted here, should result at a glance.


We just add an interface and then encapsulate our logic by implementing the interface, and we can unify the process.

Here's an important object-oriented idea: programming against the interface, not programming for implementation.

This is also the future in the programming of the time to consider more places, so as to have enough extensibility, rather than write the code dead.


In fact, there is a iterator interface in the Java Basic Library, and he has a more remove method than the interface we write ourselves.

This is the default iterator that was first mentioned, and there are many containers that maintain a self iterator within its implementation class, which we can use directly to get the iterator.

And if we need to have a similar demand, we can do it ourselves.


Iterator mode is here, if there is anything wrong in the text or even wrong place, but also hope to correct, and everyone to encourage.


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.