CompositeIterator Mode
2016-12-20 10:10:49 2 举报
组合迭代器模式
作者其他创作
大纲/内容
Dependency
Waitress
-allMenus:MenuComponent
+Waitress(MenuComponent m)+Print()+PrintVegetarianMenu()
public class NullIterator : IIterator{ public object Next() { //直接返回空 return null; } public bool HasNext() { //直接返回false return false; }}
java中的ArrayList自带迭代器!如果在其他语言中使用,需要自己创建相应的迭代器才行!
Realization
CompositeIterator
-stack:Stack
+CompositeIterator(IIterator i)+HasNext():bool+Next():object
MenuItem
-name:string-desc:string-vegetarian:bool-price:double
MenuCompent
+Add(MenuComponent m)+Remove(MenuComponent m)+GetChild(int i):MenuComponent+GetName():string+GetDescription():string+GetPrice():double+IsVegetarian():bool+Print()+CreateIterator():IIterator
Generalization
public class Waitress{ MenuComponent allMenus; public Waitress(MenuComponent ms) { this.allMenus = ms; } public void PrintMenu() { this.allMenus.Print(); } public void PrintVegetarianMenu() { IIterator iterator = this.allMenus.CreateIterator(); while(iterator.HasNext()) { MenuComponent menuComponent = (MenuComponent)iterator.Next(); try { if(menuComponent.IsVegetarian()) menuComponent.Print(); }catch(UnsupportedOperationException e) {} } }}
IIterator
+HasNext():bool+Next():object
tips: traverse any collections with compositeIteratorrun://先创建四个菜单MenuComponent lunchMenu = new Menu(\"Lunch Menu\
public CompositeIterator : IIterator{ Stack stack = new Stack(); public CompositeIterator(IIterator iterator) { this.stack.push(iterator); } public object Next() { //判断是否存在下一个元素 if(this.HasNext()) { //如果存在,获取栈顶迭代器 IIterator iterator = (IIterator) this.stack.peek(); //获得其中的下一个元素,并转换为组件抽象类 MenuComponent component = (MenuComponent) iterator.Next(); //如果该组件是个Menu if(component as Menu) { //创建该组件的迭代器,并压入栈中 stack.push(component.CreateIterator()); } //返回组件 return component(); }else{ return null; } } public bool HasNext() { //如果stack为空,返回false if(this.stack.empty()) { retrun false; }else{ //查看栈顶元素,并转换为IIterator接口 IIterator iterator = (IIterator) this.stack.peek(); //判断该迭代器中是否还有元素 if(!iterator.HasNext()) { //如果没有了,弹出堆栈, this.stack.pop(); //并递归调用HasNext() return this.HasNext(); }else{ return true; } } }}
NullIterator
Aggregation
Menu
-menuComponents:ArrayList-name:string-desc:string
0 条评论
下一页