Mooseでデザパタ - Adapterパターン
{ package Banner; use Moose; use Perl6::Say; has string => ( is => 'rw', isa => 'Str', required => 1 ); sub show_with_paren { my $self = shift; say '( ' . $self->string . ' )'; } sub show_with_aster { my $self = shift; say '* ' . $self->string . ' *'; } } { package PrintBanner; use Moose; has string => ( is => 'rw', isa => 'Str', required => 1 ); has banner => ( is => 'rw', default => sub { Banner->new( string => (shift)->string ); }, handles => { print1 => 'show_with_paren', print2 => 'show_with_aster' }, lazy => 1, ); } # 委譲を使ったAdapterパターンの実行例 # print1 print2 インターフェイスで既存の # showWithParen showWithAsterを使用している my $p = PrintBanner->new( string => "Hello" ); $p->print1; $p->print2;
Moose的なポイントは、
- handlesで委譲を実現している点
です