当前位置: 移动技术网 > IT编程>软件设计>设计模式 > Matlab迭代器模式

Matlab迭代器模式

2019年05月23日  | 移动技术网IT编程  | 我要评论

迭代器(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

  

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网