欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Matlab迭代器模式

程序员文章站 2022-11-03 19:10:34
迭代器(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