Mooseでデザパタ - Templateパターン
#!/usr/bin/env perl use strict; use warnings; # Template パターン # # Java言語で学ぶデザインパターンと同様の例題をPerl+Mooseで記述した。 # # coded by Dann { package AbstractDisplay; # 抽象クラスAbstractDisplay use Moose::Role; requires 'open'; requires 'custom_print'; requires 'close'; sub display { my $self = shift; $self->open; for ( 1 .. 5 ) { $self->custom_print; } $self->close; } } { package CharDisplay; use Moose; use Perl6::Say; with 'AbstractDisplay'; has ch => ( is => 'rw', required => 1 ); sub open { print "<"; } sub custom_print { my $self = shift; print $self->ch; } sub close { say ">"; } } { package StringDisplay; use Moose; use Perl6::Say; use Moose::Autobox; with 'AbstractDisplay'; has stringchr => ( is => 'rw', required => 1 ); sub open { my $self = shift; $self->print_line; } sub custom_print { my $self = shift; say "|" . $self->stringchr . "|"; } sub close { my $self = shift; $self->print_line; } sub print_line { my $self = shift; my $n = $self->stringchr->length; print "+"; for ( 1 .. $n ) { print "-"; } say "+"; } } sub main { my $d1 = CharDisplay->new( ch => "H" ); my $d2 = StringDisplay->new( stringchr => "Hello, world." ); my $d3 = StringDisplay->new( stringchr => "こんにちわ。" ); $d1->display; $d2->display; $d3->display; } main();
Moose的なポイントは
- 抽象クラスとしてのRole
でしょうか。
Template Methodのように一部が空実装というケースであれば、around modifireを使って実装してもよいでしょう。