我有两个需要昂贵计算的对象属性,所以我希望它们是懒惰的。它们最有效地一起计算,所以我想同时计算它们。 Moose是否提供了这样做的方法?
我想要的是“默认”或“构建器”,但不是返回默认值,而是直接设置属性。返回值将被忽略。
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;
}
注意:我可以写自己的'读者'或使用'around',但我宁愿保持声明,让Moose完成工作。我也可以创建一个新对象来存储配对值,但是对于两个值来说似乎有些过分。
答案 0 :(得分:8)
我不会说这是特别优雅,但它有效...
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;
答案 1 :(得分:6)
我通常通过将两个属性指向第三个隐藏属性来处理这个问题:
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,
};
}
答案 2 :(得分:3)
除非他们特别需要是不同的属性,否则我通常使用原生属性特征来“模拟”多个属性:
has config => (
traits => ['Hash'],
is => 'bare',
isa => 'HashRef[Str]',
lazy => 1,
# returns a hashref of key/value config pairs
builder => 'load_config',
handles => {
has_author => [ exists => 'author' ],
author => [ get => 'author' ],
has_email => [ exists => 'email' ],
email => [ get => 'email' ],
},
);
这样,昂贵的构建器只需要返回一个hashref,其中填充了“author”和“email”键;该属性将生成访问器方法,然后外观和感觉就像单个属性的那些。如果你需要在new()中单独设置它们,这可能不是最好的选择,尽管你可以使用BUILDARGS()来帮助; YMMV。
另见http://wps.io/2012/05/simulating-multiple-lazy-attributes/