Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

PerlでBuilderパターンを書いてみた。

PerlでBuilderパターンを書いてみた。

by narita_cpp
1 / 9

概要

PerlでBuilderパターンを書いてみました。


Builderパターンとは

  • オブジェクト
  • 必須パラメータ
  • optionalパラメータ

を渡すといい感じに動的にオブジェクトを作ってくれる。


wiki

Builder パターン(ビルダー・パターン)とは、GoF(Gang of Four; 4人のギャングたち)によって定義されたデザインパターンの1つである。 オブジェクトの生成過程を抽象化することによって、動的なオブジェクトの生成を可能にする。


Effective Java

コンストラクタの引数には, Builder オブジェクトを渡す。
Builder オブジェクトの引数には必須の情報を渡す。
任意の引数には, setter を用意する。

Dinner dinner  = new Dinner ("焼肉").setDrink("ビール").setDessert("アイス").build();


Perlで実装

DinnerBuilder.pm
package DinnerBuilder;
use strict;
use warnings;
use utf8;

use Mouse;

has food => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has drink => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has dessert => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has price => (
    is      => 'rw',
    isa     => 'Int',
    default => 0,
);

sub create {
    my ($class, $food) = @_;

    return $class->new(
        food    => $food,
        drink   => 'none',
        dessert => 'none',
        price   => 1000,
    );
}

sub set_drink {
    my ($self, $drink) = @_;
    $self->drink = $drink;

    $self->price += 100;
    return $self;
}

sub set_dessert {
    my ($self, $dessert) = @_;
    $self->dessert = $dessert;

    $self->price += 500;
    return $self;
}

sub build {
    my $self = shift;
    return $self;
}

sub payment {
    my $self = shift;
    return join(',', ($self->food, $self->drink, $self->dessert, $self->price));
}

no Moose;
__PACKAGE__->meta->make_immutable;

Dinner.pl
use strict;
use warnings;
use utf8;

use feature qw/say/;
use DinnerBuilder;

my $pay1 = DinnerBuilder
    ->create('Sushi')
    ->set_drink('Beer')
    ->set_dessert('Icecream')
    ->build()
    ->payment();

say $pay1;

my $pay2 = DinnerBuilder
    ->create('Sushi')
    ->build()
    ->payment();

say $pay2;

結果

$ perl Dinner.pl
Sushi,Beer,Icecream,1600
Sushi,none,none,1000

かっこよくて良いなと思いました。


Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
0
Help us understand the problem. What are the problem?