迭代器(Iterator)模式,又叫做游标(Cursor)模式。提供一种方法访问一个容器(container)或者聚集(Aggregator)对象中各个元素,而又不需暴露该对象的内部细节。在采用不同的方式迭代时,只需要替换相应Iterator类即可。本文采用Matlab语言实现对元胞数组和string数组的遍历。
Aggregator.m
classdef Aggregator < handle methods(Abstract) iterObj = createIterator(~); end end
CellAggregator.m
classdef CellAggregator < Aggregator properties cell end methods function obj = CellAggregator(cell) obj.cell = cell; end function iterObj = createIterator(obj) iterObj = CellIterator(obj); end end end
StringAggregator.m
classdef StringAggregator < Aggregator properties string_arr end methods function obj = StringAggregator(string_arr) obj.string_arr = string_arr; end function iterObj = createIterator(obj) iterObj = StringIterator(obj); end end end
Iterator.m
classdef Iterator < handle methods(Abstract) hasNext(~); next(~); end end
CellIterator.m
classdef CellIterator < Iterator properties index = 1; aggHandle; end methods function obj = CellIterator(agg) obj.aggHandle = agg; end function res = hasNext(obj) if(obj.index <= length(obj.aggHandle.cell)) res = true; else res = false; end end function ele = next(obj) if(obj.hasNext()) ele = obj.aggHandle.cell{obj.index}; obj.index = obj.index + 1; else ele = []; end end end end
StringIterator.m
classdef StringIterator < Iterator properties index = 1; aggHandle; end methods function obj = StringIterator(agg) obj.aggHandle = agg; end function res = hasNext(obj) if(obj.index <= obj.aggHandle.string_arr.length) res = true; else res = false; end end function ele = next(obj) if(obj.hasNext()) ele = obj.aggHandle.string_arr(obj.index); obj.index = obj.index + 1; else ele = string.empty(); end end end end
测试代码:
cell = CellAggregator({'matlab','cell','iter'}); iterObj = cell.createIterator(); while iterObj.hasNext() disp(iterObj.next()); end str_arr = StringAggregator(["matlab","string","iter"]); iterObj = str_arr.createIterator(); while iterObj.hasNext() disp(iterObj.next()); end