Delegates: Difference between revisions

Line 765:
}
1;
 
 
package main;
Line 777 ⟶ 778:
# With delegate that implements "thing"
$a->{delegate} = Delegate->new;
$a->operation eq 'delegate implementation' or die;</lang>
</lang>
 
Using Moose.
 
<lang perl>
use 5.010_000;
 
package Delegate::Protocol
use Moose::Role;
 
=pod
The Object claiming to do this role will have a
thing method.
=cut
requires 'thing';
# optional methods are not described, this is just for
# the reader of the code.
# optional 'optional_thing'
 
package Delegate;
use Moose;
 
# The we confirm to Delegate::Protocol
with 'Delegate::Protocol';
 
sub thing { 'delegate implementation' };
 
package Delegate2;
use Moose;
 
# The we confirm to Delegate::Protocol
with 'Delegate::Protocol';
 
sub thing { 'delegate2 implementation' };
sub optional_thing { ' with optional thing' };
 
package Delegator;
use Moose;
 
has delegate => (
is => 'rw',
does => 'Delegate::Protocol', # Moose insures that the delegate confirms to the role.
predicate => 'hasDelegate'
);
 
sub operation {
my ($self) = @_;
if( $self->hasDelegate ){
my $delegate = $self->delegate;
my $postfix = '';
$postfix = $delegate->optional_thing() if( $delegate->can('optional_thing') );
return $delegate->thing() . $postfix; # we are know that delegate has thing.
} else {
return 'default implementation';
}
};
 
package main;
use strict;
 
my $delegator = Delegator->new();
$delegator->operation eq 'default implementation' or die;
 
# With delegate that implements "thing" and not "optional_thing"
$delegator->delegate( Delegate->new );
$delegator->operation eq 'delegate implementation' or die;
 
# With a delegate that implements "thing" and "optional_thing"
$delegator->{delegate} = Delegate2->new;
$delegator->operation eq 'delegate2 implementation with optional thing' or die;
 
=={{header|Perl 6}}==
Anonymous user