views:

382

answers:

3

How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.

+3  A: 

Use sub references, and closures. A good perlish example of this

sort { lc($a) cmp lc($b) } @items
Leon Timmermans
+3  A: 

This article may be of some use. It covers an example of using the strategy pattern in Perl. http://www.perl.com/pub/a/2003/08/07/design2.html

mopoke
+2  A: 

It really depends on what you mean by "clean implementation". As in any other language, you can use Perl's object system with polymorphism to do this for you. However, since Perl has first class functions, this pattern isn't normally coded explicitly. Leon Timmermans' example of

sort { lc($a) cmp lc($b) } @items

demonstrates this quite elegantly.

However, if you're looking for a "formal" implementation as you would do in C++, here's what it may look like using Perl+Moose. This is just a translation of the C++ code from Wikipedia -- Strategy pattern, except I'm using Moose's support for delegation.

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();
tsee