Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean implementation of the strategy pattern in Perl

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.

like image 569
sutee Avatar asked Nov 17 '25 21:11

sutee


2 Answers

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();
like image 116
tsee Avatar answered Nov 20 '25 13:11

tsee


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

sort { lc($a) cmp lc($b) } @items
like image 44
Leon Timmermans Avatar answered Nov 20 '25 12:11

Leon Timmermans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!