Moose:角色中的共享属性
Posted
技术标签:
【中文标题】Moose:角色中的共享属性【英文标题】:Moose: Share attribute in role 【发布时间】:2015-02-20 11:14:47 【问题描述】:我想在角色中声明一个属性,并且它的值在使用该角色的所有类实例之间共享。
我已经写了这个,但我认为这不是更好的方法:
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】:此解决方案取消了额外的 RealResource 类。该角色被转换为一个类,以便它可以共享类属性。 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,$/;
【讨论】:
以上是关于Moose:角色中的共享属性的主要内容,如果未能解决你的问题,请参考以下文章
Azure Fabric 服务中的不同辅助角色是不是共享对象?
如何解决:关系约束中的从属角色和主要角色中的属性数量必须相同?