我有两个对象属性需要昂贵的计算,所以我希望它们是懒惰的.它们最有效地一起计算,所以我想同时计算它们.穆斯是否提供了这样做的方法?
我想要的是"默认"或"构建器",但不是返回默认值,而是直接设置属性.返回值将被忽略.
has max_things =>
is => 'rw',
isa => 'Int',
lazy => 1,
xxxxx => '_set_maxes';
has max_pairs =>
is => 'rw',
isa => 'Int',
lazy => 1,
xxxxx => '_set_maxes';
# Let's just assume this is an expensive calculation or the max_*
# attributes are used rarely and a lot of objects are created.
sub _set_maxes {
my $self = shift;
if( $self->is_32_bit ) {
$self->max_things(2**31);
$self->max_pairs(12345 * 2);
}
else {
$self->max_thing(2**63);
$self->max_pairs(23456 * 2);
}
return;
}
Run Code Online (Sandbox Code Playgroud)
注意:我可以写自己的'读者'或使用'around',但我宁愿保持声明,让Moose完成工作.我也可以创建一个新对象来存储配对值,但对于两个值来说似乎有些过分.
我不会说这是特别优雅,但它有效......
use v5.14;
use warnings;
package Goose {
use Moose;
has max_things => (
is => 'rw',
isa => 'Int',
lazy => 1,
default => sub { shift->_build_maxes->max_things },
);
has max_pairs => (
is => 'rw',
isa => 'Int',
lazy => 1,
default => sub { shift->_build_maxes->max_pairs },
);
sub is_32_bit { 1 }
sub _build_maxes {
my $self = shift;
warn "Running builder...";
if( $self->is_32_bit ) {
$self->max_things(2**31);
$self->max_pairs(12345 * 2);
}
else {
$self->max_thing(2**63);
$self->max_pairs(23456 * 2);
}
$self; # helps chaining in the defaults above
}
}
my $goose = Goose->new;
say $goose->max_things;
say $goose->max_pairs;
Run Code Online (Sandbox Code Playgroud)
我通常通过将两个属性指向第三个隐藏属性来处理此问题:
has 'max_things' => (
'is' => "rw",
'isa' => "Int",
'lazy' => 1,
'default' => sub { (shift)->_both_maxes->{'max_things'} },
);
has 'max_pairs' => (
'is' => "rw",
'isa' => "Int",
'lazy' => 1,
'default' => sub { (shift)->_both_maxes->{'max_pairs'} },
);
has '_both_maxes' => (
'is' => "ro",
'isa' => "HashRef",
'lazy' => 1,
'builder' => "_build_both_maxes",
);
sub _build_both_maxes {
my $self = shift;
my ($max_things, $max_pairs);
if($self->is_32_bit) {
$max_things = 2 ** 31;
$max_pairs = 12345 * 2;
}
else {
$max_things = 2 ** 63;
$max_pairs = 23456 * 2;
}
return {
'max_things' => $max_things,
'max_pairs' => $max_pairs,
};
}
Run Code Online (Sandbox Code Playgroud)