Hatena::Groupdann

dann's blog このページをアンテナに追加 RSSフィード

Fork me on GitHub

2008-05-31

Mooseでデザパタ - Factory Methodパターン

| Mooseでデザパタ - Factory Methodパターン - dann's blog を含むブックマーク はてなブックマーク - Mooseでデザパタ - Factory Methodパターン - dann's blog Mooseでデザパタ - Factory Methodパターン - dann's blog のブックマークコメント

# Factory Method パターン
#
# Java言語で学ぶデザインパターンと同様の例題をPerl+Mooseで記述した。
#
# coded by Dann
#

{

    package Product;
    use Moose::Role;
    requires 'use';
}

{

    package Factory;
    use Moose::Role;
    requires 'create_product';
    requires 'register_product';

    sub create {
        my ( $self, $owner ) = @_;
        my $p = $self->create_product($owner);
        $self->register_product($p);
        $p;
    }
}

{

    package IDCard;
    use Moose;
    use Perl6::Say;
    with 'Product';
    has owner => ( is => 'rw', required => 1 );

    sub use {
        my $self = shift;
        say $self->owner . "のカードを使います";
    }
}

{

    package IDCardFactory;
    use Moose;
    use Moose::Autobox;
    with 'Factory';
    has owners => ( is => 'rw', isa => 'ArrayRef', default => sub { [] } );

    sub create_product {
        my ( $self, $owner ) = @_;
        IDCard->new( owner => $owner );
    }

    sub register_product {
        my ( $self, $product ) = @_;
        $self->owners->push( $product->owner );
    }
}

sub main {
    my $factory = IDCardFactory->new;
    my $card1   = $factory->create("結城浩");
    my $card2   = $factory->create("とむら");
    my $card3   = $factory->create("佐藤花子");
    $card1->use;
    $card2->use;
    $card3->use;
}

main();