Debuginfo

思考とアウトプット

Strategy Pattern on Perl + Moose

StackoverflowのAnswerが秀逸すぎて思わずコピペ。

http://stackoverflow.com/questions/78278/clean-implementation-of-the-strategy-pattern-in-perl

package StrategyInterface;
use Moose::Role;
requires 'run';


package Context;
use Moose;
has 'strategy' => (
  is      => 'rw',
  isa     => 'StrategyInterface',
  handles => [ 'run' ],
);


package SomeStrategy;
use Moose;
with 'StrategyInterface';
sub run { warn "applying SomeStrategy!\n"; }


package AnotherStrategy;
use Moose;
with 'StrategyInterface';
sub run { warn "applying AnotherStrategy!\n"; }


###############
package main;
my $contextOne = Context->new(
  strategy => SomeStrategy->new()
);

my $contextTwo = Context->new(
  strategy => AnotherStrategy->new()
);

$contextOne->run();
$contextTwo->run();