package Trouble;
use Moose;
has number => ( isa => 'Str', is => 'ro');
sub getNumber {
my $self = shift;
return $self->number;
}
sub toString {
my $self = shift;
return "[Trouble " . $self->number . "]";
}
package Support;
use Moose::Role;
use Perl6::Say;
requires 'resolve';
has name => (isa => 'Str', is => 'rw', required => 1);
has next => (isa => 'Support', is => 'rw');
sub setNext {
my ($self, $next) = @_;
$self->next($next);
return $next;
}
sub support {
my ($self, $trouble) = @_;
if($self->resolve($trouble)) {
$self->done($trouble);
}
elsif(defined($self->next)) {
$self->next->support($trouble);
} else {
$self->fail($trouble);
}
}
sub toString {
my $self = shift;
return "[" . $self->name . "]";
}
sub done {
my( $self, $trouble ) = @_;
say $trouble->toString() . " is resolved by " . $self->toString . ".";
}
sub fail {
my( $self, $trouble ) = @_;
say $trouble->toString() . " cannnot be resolved.";
}
package NoSupport;
use Moose;
with 'Support';
sub resolve { return 0; }
package LimitSupport;
use Moose;
with 'Support';
has limit => (isa => 'Int', is => 'rw', required => 1);
sub resolve {
my ($self, $trouble) = @_;
if($trouble->getNumber() < $self->limit) {
return 1;
}
else {
return 0;
}
}
package SpecialSupport;
use Moose;
with 'Support';
has number => (isa => 'Int', is => 'rw', required => 1);
sub resolve {
my ($self, $trouble) = @_;
if($trouble->getNumber() == $self->number) {
return 1;
}
else {
return 0;
}
}
package OddSupport;
use Moose;
with 'Support';
sub resolve {
my ($self, $trouble) = @_;
if($trouble->getNumber() % 2 == 1) {
return 1;
}
else {
return 0;
}
}
package main;
use Perl6::Say;
my $alice = NoSupport->new(name => "Alice");
my $bob = LimitSupport->new(name => "Bob", limit => 100);
my $charlie = SpecialSupport->new(name => "Charlie", number => 429);
my $diana = LimitSupport->new(name => "Diana", limit => 200);
my $elmo = OddSupport->new(name => "Elmo");
my $fred = LimitSupport->new(name => "Fred", limit => 300);
$alice->setNext($bob)->setNext($charlie)
->setNext($diana)->setNext($elmo)->setNext($fred);
for(my $i=0;$i<500;$i+=33){
$alice->support(Trouble->new( number => $i));
}
実行
[Trouble 0] is resolved by [Bob].
[Trouble 33] is resolved by [Bob].
[Trouble 66] is resolved by [Bob].
[Trouble 99] is resolved by [Bob].
[Trouble 132] is resolved by [Diana].
[Trouble 165] is resolved by [Diana].
[Trouble 198] is resolved by [Diana].
[Trouble 231] is resolved by [Elmo].
[Trouble 264] is resolved by [Fred].
[Trouble 297] is resolved by [Elmo].
[Trouble 330] cannnot be resolved.
[Trouble 363] is resolved by [Elmo].
[Trouble 396] cannnot be resolved.
[Trouble 429] is resolved by [Charlie].
[Trouble 462] cannnot be resolved.
[Trouble 495] is resolved by [Elmo].