Moose:在角色中共享属性

时间:2015-02-20 11:14:48

标签: perl moose

我希望在一个Role中有一个属性声明,并且它的值在所有使用该角色的类的实例之间共享。

我写过这个,但我认为这不是更好的方法:

package RealRessource;
use Moose;
use MooseX::ClassAttribute;
class_has '_real_ressource' => ( is => 'ro', isa => 'Int', lazy => 1,
                                 builder => '_build_real_ressource' );

sub _build_real_ressource {
    print "_build_real_ressource\n";
    return int(rand(100));
}
__PACKAGE__->meta->make_immutable;

package ShareRessource;
use Moose::Role;
has 'ressource' => ( is => 'ro', isa => 'Int', lazy => 1,
                     builder => '_build_ressource' );

sub _build_ressource {
    print "Build New Ressource\n";
    my $real_ressource = new RealRessource();
    return $real_ressource->_real_ressource;
}

package A;
use Moose;

with 'ShareRessource';

__PACKAGE__->meta->make_immutable;

package B;
use Moose;

with 'ShareRessource';

__PACKAGE__->meta->make_immutable;

package main;
use A;
use B;

my $a = new A();
my $b = new B();
print $a->ressource,$/;
print $b->ressource,$/;

结果是:

Build New Ressource
_build_real_ressource
28
Build New Ressource
28

1 个答案:

答案 0 :(得分:0)

此解决方案取消了额外的RealResource类。该角色已转换为类,以便它可以共享class属性。 MooseX::ABC的使用是可选的,但我把它放在那里强制它无法实​​例化。

package ShareResource;
use Moose;
use MooseX::ABC;
use MooseX::ClassAttribute;
class_has 'resource' => (
    is      => 'ro',
    isa     => 'Int',
    lazy    => 1,
    builder => '_build_resource',
);
sub _build_resource {
    print "_build_resource\n";
    return int(rand(100));
}
__PACKAGE__->meta->make_immutable;

package A;
use Moose;
extends 'ShareResource';
__PACKAGE__->meta->make_immutable;

package B;
use Moose;
extends 'ShareResource';
__PACKAGE__->meta->make_immutable;

package main;
use A;
use B;

my $a = A->new();
my $b = B->new();
print $a->resource,$/;
print $b->resource,$/;