迭代器(Iterator)模式,又叫做游標(Cursor)模式。提供一種方法訪問一個容器(container)或者聚集(Aggregator)對象中各個元素,而又不需暴露該對象的內部細節。在採用不同的方式迭代時,只需要替換相應Iterator類即可。本文采用Matlab語言實現對元胞數組和strin ...
迭代器(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