Markrh:PerlProgramming:StrategyPattern
From BluWiki
Contents |
Code, TRAVEL.pm
package TRAVEL;
use COWBOY;
use HORSE;
# --------------------------------------------- create
sub create {
my $type = shift;
if (lc($type) eq 'horse') {
return new HORSE;
}
elsif (lc($type) eq 'cowboy') {
return new COWBOY;
}
else {
die "Bad type [$type]\n";
}
}
# --------------------------------------------- doIt
sub doIt() {
my $self = shift;
print "TRAVEL. doIt()\n";
print "foo: ", $self->{foo}, "\n";
}
1;
Code, COWBOY.pm
package COWBOY;
use TRAVEL;
@ISA = qw(TRAVEL);
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->{'foo'} = 'bar';
return $self;
}
sub travel {
print "mosey\n";
}
1;
Code, HORSE.pm
package HORSE;
use TRAVEL;
@ISA = qw(TRAVEL);
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->{'foo'} = 'too';
return $self;
}
sub travel {
print "gallop\n";
}
1;
Code, client.pl
#!/perl -w use strict; use TRAVEL; my $o = TRAVEL::create($ARGV[0]); $o->travel; $o->doIt;
Output
./client.pl horse gallop TRAVEL. doIt() foo: too ... ... ./client.pl cowboy mosey TRAVEL. doIt() foo: bar
Categories: Perl Programming-Cookbook, Markrh:DesignPatterns



