【发布时间】:2012-01-28 08:03:49
【问题描述】:
假设我有两个角色:Simple::Tax 和 Real::Tax。在测试情况下,我想使用 Simple::Tax,而在生产环境中,我想使用 Real::Tax。做这个的最好方式是什么?我的第一个想法是使用不同版本的new 方法来创建具有不同角色的对象:
#!/usr/bin/perl
use warnings;
{
package Simple::Tax;
use Moose::Role;
requires 'price';
sub calculate_tax {
my $self = shift;
return int($self->price * 0.05);
}
}
{
package A;
use Moose;
use Moose::Util qw( apply_all_roles );
has price => ( is => "rw", isa => 'Int' ); #price in pennies
sub new_with_simple_tax {
my $class = shift;
my $obj = $class->new(@_);
apply_all_roles( $obj, "Simple::Tax" );
}
}
my $o = A->new_with_simple_tax(price => 100);
print $o->calculate_tax, " cents\n";
我的第二个想法是在包体中使用 if 语句来使用不同的 with 语句:
#!/usr/bin/perl
use warnings;
{
package Complex::Tax;
use Moose::Role;
requires 'price';
sub calculate_tax {
my $self = shift;
#pretend this is more complex
return int($self->price * 0.15);
}
}
{
package Simple::Tax;
use Moose::Role;
requires 'price';
sub calculate_tax {
my $self = shift;
return int($self->price * 0.05);
}
}
{
package A;
use Moose;
has price => ( is => "rw", isa => 'Int' ); #price in pennies
if ($ENV{TEST_A}) {
with "Simple::Tax";
} else {
with "Complex::Tax";
}
}
my $o = A->new(price => 100);
print $o->calculate_tax, " cents\n";
其中一个比另一个更好吗?它们中的任何一个有什么可怕的地方吗?有没有更好的方法我还没有想到。
【问题讨论】: