Iteratorパターン

オブジェクト指向プログラミングを身に付けるためには、デザインパターンを勉強するのが一番です。というわけでPerlデザインパターンを実装してみます。

元ネタは こちら から拝借しました。元ネタはshift;を多用していたのですが、C++Javaっぽく@_;を使ったものに書き換えました。

ソース

Aggregate.pm
package Aggregate;
use strict;

sub iterator { die; }

1;
Iterator.pm
package Iterator;
use strict;

sub next { die; }
sub hasnext { die; }

1;
Book.pm
package Book;
use strict;

sub new {
    my ($class, $name) = @_;
    my $self = {};
    $self->{name} = $name;
    bless $self, $class;
}

sub getname {
    my ($self) = @_;
    return $self->{name};
}

1;
BookShelf.pm
package BookShelf;
use strict;
use base qw(Aggregate);
use BookShelfIterator;

sub new {
    my ($class, $maxsize) = @_;
    my $self = {};
    $self->{maxsize} = $maxsize;
    $self->{books} = [];
    $self->{last} = 0;
    bless $self, $class;
}

sub get_book_at {
    my ($self, $index) = @_;
    return $self->{books}->[$index];
}

sub appendbook {
    my ($self, $book) = @_;
    $self->{books}->[$self->{last}] = $book;
    $self->{last}++;
}

sub getlength {
    my ($self) = @_;
    return $self->{last};
}

sub iterator {
    my ($self) = @_;
    return BookShelfIterator->new($self);
}

1;
BookShelfIterator.pm
package BookShelfIterator;
use strict;
use base qw(Iterator);

sub new {
    my ($class, $bookshelf) = @_;
    my $self = {};
    $self->{bookshelf} = $bookshelf;
    $self->{index} = 0;
    bless $self, $class;
}

sub hasnext {
    my ($self) = @_;
    return ($self->{index} < $self->{bookshelf}->getlength) ? 1 : 0;
}

sub next {
    my ($self) = @_;
    my $book = $self->{bookshelf}->get_book_at($self->{index});
    $self->{index}++;
    return $book;
}

1;
main.pl
#!/usr/bin/perl
use strict;

use BookShelf;
use Book;

my $bookshelf = BookShelf->new(5);
$bookshelf->appendbook
(Book->new('Java言語で学ぶデザインパターン入門'));
$bookshelf->appendbook
(Book->new('憂鬱なプログラマのためのオブジェクト指向開発講座'));
$bookshelf->appendbook
(Book->new('Design Patterns Elements of Reusable 
Object-Oriented Software'));
$bookshelf->appendbook
(Book->new('かんたんUML'));
$bookshelf->appendbook
(Book->new('プログラミングPerl'));
$bookshelf->appendbook
(Book->new('オブジェクト指向Perlマスターコース'));
my $it = $bookshelf->iterator;

while ($it->hasnext) {
    my $book = $it->next;
    print $book->getname()."\n";
}

実行結果

[hogehoge@localhost Iterator]$ perl main.pl
Java言語で学ぶデザインパターン入門
憂鬱なプログラマのためのオブジェクト指向開発講座
Design Patterns Elements of Reusable Object-Oriented Software
かんたんUML
プログラミングPerl
オブジェクト指向Perlマスターコース