code_junkie

Clean implementation of the strategy pattern in Perl

Nov 10th, 2011
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. sort { lc($a) cmp lc($b) } @items
  2.  
  3. package StrategyInterface;
  4. use Moose::Role;
  5. requires 'run';
  6.  
  7.  
  8. package Context;
  9. use Moose;
  10. has 'strategy' => (
  11. is => 'rw',
  12. isa => 'StrategyInterface',
  13. handles => [ 'run' ],
  14. );
  15.  
  16.  
  17. package SomeStrategy;
  18. use Moose;
  19. with 'StrategyInterface';
  20. sub run { warn "applying SomeStrategy!n"; }
  21.  
  22.  
  23. package AnotherStrategy;
  24. use Moose;
  25. with 'StrategyInterface';
  26. sub run { warn "applying AnotherStrategy!n"; }
  27.  
  28.  
  29. ###############
  30. package main;
  31. my $contextOne = Context->new(
  32. strategy => SomeStrategy->new()
  33. );
  34.  
  35. my $contextTwo = Context->new(
  36. strategy => AnotherStrategy->new()
  37. );
  38.  
  39. $contextOne->run();
  40. $contextTwo->run();
  41.  
  42. sort { lc($a) cmp lc($b) } @items
Add Comment
Please, Sign In to add comment