Pure implementation of a strategy template in Perl

How to write a clean implementation of a strategy template in Perl? I want to do this in order to use Perl functions.

+3
source share
3 answers

It really depends on what you mean by “pure implementation”. As in any other language, you can use the Perl object system with polymorphism to do this for you. However, since Perl has first-class functions, this pattern is usually not explicitly encoded. Leon Timmermans example

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

demonstrates this quite elegantly.

, "" , ++, Perl + Moose. ++ - , , Moose .

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();
+5

.

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

This article may come in handy. It covers an example of using a strategy template in Perl. http://www.perl.com/pub/a/2003/08/07/design2.html

+3
source

Source: https://habr.com/ru/post/1697003/


All Articles