我有两个对象属性需要昂贵的计算,所以我希望他们懒惰.它们最有效地计算在一起,所以我想同时计算它们.麋鹿是否提供了一种方法?
我想要的是“默认”或“构建器”,而不是返回默认值,它直接设置属性.返回值将被忽略.
has max_things => is => 'rw',isa => 'Int',lazy => 1,xxxxx => '_set_maxes'; has max_pairs => is => 'rw',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; }
注意:我可以写我自己的“读者”或使用“周围”,但我宁愿保持声明,让Moose做这个工作.我也可以创建一个新对象来存储配对的值,但是对于两个值似乎是过度的.
解决方法
我不会说这是特别优雅,但它的作品…
use v5.14; use warnings; package Goose { use Moose; has max_things => ( is => 'rw',default => sub { shift->_build_maxes->max_things },); has max_pairs => ( is => 'rw',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;