Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example Builder Pattern in Moose ("http://en.wikipedia.org/wiki/Builder_pattern")
use Test::Most;
{
package Pizza;
use Moose;
has [qw/dough sauce topping/] => (is=>'rw');
package PizzaBuilder;
use Moose::Role;
requires qw/build_dough build_sauce build_topping/;
has pizza => (is=>'ro', isa=>'Pizza',
builder=>'_build_pizza', required=>1);
sub _build_pizza { Pizza->new }
package HawaiianPizzaBuilder;
use Moose;
with 'PizzaBuilder';
sub build_dough { shift->pizza->dough('cross') }
sub build_sauce { shift->pizza->sauce('mild') }
sub build_topping { shift->pizza->topping('ham+pineapple') }
package SpicyPizzaBuilder;
use Moose;
with 'PizzaBuilder';
sub build_dough { shift->pizza->dough('pan baked') }
sub build_sauce { shift->pizza->sauce('hot') }
sub build_topping { shift->pizza->topping('pepperoni+salami') }
package Waiter;
use Moose;
has 'pizza_builder' => (is=>'rw', does=>'PizzaBuilder');
sub pizza { shift->pizza_builder->pizza }
sub construct_pizza {
my ($self) = @_;
$self->pizza_builder->$_ for (qw/
build_dough build_sauce build_topping/);
}
}
ok my $waiter = Waiter->new;
ok my $hawaiian_pizza_builder = HawaiianPizzaBuilder->new;
ok my $spicy_pizza_builder = SpicyPizzaBuilder->new;
for($waiter) {
$_->pizza_builder($hawaiian_pizza_builder);
$_->construct_pizza;
}
is $waiter->pizza->sauce, 'mild';
for($waiter) {
$_->pizza_builder($spicy_pizza_builder);
$_->construct_pizza;
}
is $waiter->pizza->sauce, 'hot';
done_testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.