概要
Iterator パターンは、複数の要素を順番に指し示し、全体をスキャンしていく、デザインパターンの一つである。
ソースコード
Aggregate.m
classdef (Abstract) Aggregate < handle
methods (Abstract)
out = iterator(obj)
end
end
Iterator.m
classdef (Abstract) Iterator < handle
methods (Abstract)
out = hasNext(obj);
out = next(obj);
end
end
Book.m
classdef Book < handle
properties(Access = private)
name char {mustBeTextScalar} = ''
end
methods (Access = public)
function obj = Book(name)
arguments (Input)
name char {mustBeTextScalar}
end
arguments (Output)
obj (1,1) Book
end
obj.name = name;
end
function name = getName(obj)
arguments (Input)
obj (1,1) Book
end
arguments (Output)
name char {mustBeTextScalar}
end
name = obj.name;
end
end
end
BookShelf.m
classdef BookShelf < Aggregate
properties (Access = private)
books (1,:) Book
last (1,1) int32 = 1
end
methods (Access = public)
function obj = BookShelf(maxsize)
arguments (Input)
maxsize (1,1) double {mustBeInteger}
end
arguments (Output)
obj (1,1) BookShelf
end
obj.books = matlab.lang.invalidHandle('Book', 1, maxsize);
end
function book = getBookAt(obj, index)
arguments (Input)
obj (1,1) BookShelf
index (1,1) double {mustBeInteger}
end
arguments (Output)
book (1,1) Book
end
book = obj.books(index);
end
function appendBook(obj, book)
arguments (Input)
obj (1,1) BookShelf
book (1,1) Book
end
obj.books(obj.last) = book;
obj.last = obj.last + 1;
end
function last = getLength(obj)
arguments (Input)
obj (1,1) BookShelf
end
arguments (Output)
last (1,1) double {mustBeInteger}
end
last = obj.last;
end
function out = iterator(obj)
arguments (Input)
obj (1,1) BookShelf
end
arguments (Output)
out (1,1) BookShelfIterator
end
out = BookShelfIterator(obj);
end
end
end
BookShelfIterator.m
classdef BookShelfIterator < Iterator
properties (Access = private)
bookShelf (1,1) BookShelf = matlab.lang.invalidHandle('BookShelf', 1, 1)
index int32 = 1
end
methods (Access = public)
function obj = BookShelfIterator(bookShelf)
arguments (Input)
bookShelf (1,1) BookShelf
end
arguments (Output)
obj (1,1) BookShelfIterator
end
obj.bookShelf = bookShelf;
end
function out = hasNext(obj)
arguments (Input)
obj (1,1) BookShelfIterator
end
arguments (Output)
out (1,1) logical
end
out = obj.index < obj.bookShelf.getLength();
end
function out = next(obj)
arguments (Input)
obj (1,1) BookShelfIterator
end
arguments (Output)
out (1,1) Book
end
out = obj.bookShelf.getBookAt(obj.index);
obj.index = obj.index + 1;
end
end
end
main.m
function main
bookShelf = BookShelf(4);
bookShelf.appendBook(Book('Around the World in 80 Days'));
bookShelf.appendBook(Book('Bible'));
bookShelf.appendBook(Book('Cinderella'));
bookShelf.appendBook(Book('Daddy-Long-Legs'));
it = bookShelf.iterator();
while it.hasNext()
book = it.next();
disp(book.getName());
end
end
実行結果
>> main
Around the World in 80 Days
Bible
Cinderella
Daddy-Long-Legs