资源描述:
《Iterator 迭代器模式》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、Iterator迭代器特大喜讯,PancakeHouse(薄烤饼屋)早餐店和Diner(用餐者)午餐店合并了,您现在可以在一个地方享受到美味的早餐和午餐。哥们!我想用ArrayList列我的PancakeHouse为早餐菜单,Diner为你的午餐菜单,如何?靠!我不干,我喜欢用Array两份菜列表实现很简单三个类搞定MenuItem类PubliccalssMenuItem{Stringname;Stringdescription;Booleanvegetarian;//是否素食的doubleprice;PublicMenuItem(Stringname,Stringdesc
2、ription,booleanvegetarian,doubleprice){}//所有属性有get方法}PancakeHouse的菜单PublicclassPancakeHouseMenu{ArrayListmenuItems=newArrayList();PublicPancakeHouse(){addItem(“K&B’sPancakeBreakfast”,”Pancakeswithscrambledeggs,andtoast”,true,2,99);}PublicvoidaddItem(Stringname,Stringdescription,booleanvege
3、tarian,doubleprice){MenuItemmenuItem=newMenuItem(Stringname,Stringdescription,booleanvegetarian,doubleprice);menuItems.add(menuItem);}PublicArrayListgetMenuItems(){returnmenuItems;}}增加菜单项菜单项增加到列表中返回菜单列表DinerMenu菜单PublicclassDinerMenu(staticfinalintMAX_ITEMS=6;intnumberOfItems=0;MenuItem[]m
4、enuItems=newMenuItem[MAX_ITEMS];PublicDinerMenu(){addItem(“VegetarianBLT”,”Baconwithlettuce&tomatoonwholewheat”,true,2,99);}PublicvoidaddItem(Stringname,Stringdescription,booleanvegetarian,doubleprice){MenuItemmenuItem=newMenuItem(Stringname,Stringdescription,booleanvegetarian,doubleprice)
5、;if(numberOfItems>=MAX_ITEMS){System.err.printer(“sorrymenuisfull!”);}else{menuItems[numberOfItems]=menuItem;numberOfItems=numberOfItems+1;}}PublicArrayListgetMenuItems(){returnmenuItems;}}如果你是服务员,你是如何展现这两份不同的菜单?并且还能说明菜单项是否是蔬食类。产生一个服务员类,其方法如下:printMenu():打印菜单上的每一列printBreakfastMenu():打印早餐列
6、printLunchMenu():打印午餐列printVegetarianMenu():打印所有蔬食类列isItemVegetarian(name):根据名字得到其是否是蔬食类的列可以列出菜单了一、PancakeHouseMenupancake=newpancakeHouseMenu();ArrayListbreakfastItems=pancake.getMenuItems();DinerMenudine=newDineerMenu();MenuItem[]lunchItems=dinerMenu.getMenuItems();注意:它返回的类型不同二、For(inti=
7、0;i