首页 > 学院 > 开发设计 > 正文

java设计模式之迭代器模式

2019-11-14 10:49:05
字体:
来源:转载
供稿:网友

迭代器模式:提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。

类图: 这里写图片描述 使用迭代器模式,实现了烤鱼菜单,类图: 这里写图片描述 MenuItem类代码实现:

public class MenuItem { String name; public MenuItem(String name){ this.name = name; } public String getname(){ return name; }}

接口Iterator代码实现:

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

类FishIterator代码实现:

public class FishIterator implements Iterator{ MenuItem[] items; int position = 0; public FishIterator(MenuItem[] items){ this.items = items; } @Override public boolean hasNext() { // TODO Auto-generated method stub if (position >=items.length || items[position] == null) { return false; }else { return true; } } @Override public Object next() { // TODO Auto-generated method stub MenuItem menuItem = items[position]; position = position + 1; return menuItem; } @Override public void remove() { // TODO Auto-generated method stub for (int i = position; i < (items.length -1); i++) { items[i] = items[i+1]; } items[items.length - 1] = null; }}

接口Menu代码实现:

public interface Menu { public Iterator createIterator();}

类FishMenu代码实现:

public class FishMenu implements Menu{ MenuItem[] items; static final int MAX_ITEMS = 6; int numberOfItems = 0; public FishMenu(){ items = new MenuItem[MAX_ITEMS]; addItem("烤鲫鱼"); addItem("烤草鱼"); addItem("烤大头鱼"); addItem("烤秋刀鱼"); addItem("烤鲨鱼"); } public void addItem(String name){ MenuItem menuItem = new MenuItem(name); if (numberOfItems >= MAX_ITEMS) { System.out.PRintln("Sorry,menu if full!can't add item to menu"); }else { //System.out.println("menuItem="+menuItem); items[numberOfItems] = menuItem; numberOfItems = numberOfItems + 1; } } @Override public Iterator createIterator() { // TODO Auto-generated method stub return new FishIterator(items); }}

类Client代码实现:

public class Client { Menu fisMenu; public Client(Menu fishMenu){ this.fisMenu = fishMenu; } public void printMenu(){ Iterator fishIterator = fisMenu.createIterator(); printMenu(fishIterator); } public void printMenu(Iterator iterator){ while (iterator.hasNext()) { MenuItem menuItem = (MenuItem)iterator.next(); System.out.println(menuItem.getname()); } }}

测试类MenuTest代码实现:

public class MenuTest { public static void main(String[] args){ Menu fishMenu = new FishMenu(); Client client = new Client(fishMenu); client.printMenu(); }}

执行结果:

烤鲫鱼烤草鱼烤大头鱼烤秋刀鱼烤鲨鱼
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表