【问题标题】:Changing Attribute values in an immutable class using Moose使用 Moose 更改不可变类中的属性值
【发布时间】:2014-04-18 22:34:54
【问题描述】:

我对 Moose 还很陌生,并且一直在努力遵循最佳做法。我知道我们应该尽可能让类不可变。我的问题是,在对象构造之后,我们可以使用 setter 更改公共属性的值并且仍然让类是不可变的吗?

【问题讨论】:

  • 根据@amon 的回答,__PACKAGE__->meta->make_immutable 使 class 不可变,而不是使 instances 不可变。但我要补充一点,使实例不可变(通过使属性只读)通常也是一个好主意。可变实例可能导致远距离操作(如果您的代码的两个部分持有对同一对象的引用,则一个可以对对象进行更改,另一个将看到这些更改),这可能导致代码更难调试.可变实例有时是必要的,但如果可能,您应该尝试设计代码以避免它们。

标签: perl moose


【解决方案1】:

是的。如果一个类是不可变的,这仅意味着我们不能向该类添加新属性或新方法。这允许 Moose 系统做一些巧妙的优化。

类的任何实例仍然可以被变异。为了使实例也是不可变的,所有属性都必须是只读的 (is => 'ro')。

例子:

package MyClass;
use Moose;

has attr => (is => 'rw'); # this attribute is read-write

__PACKAGE__->meta->make_immutable;
# after this, no new attributes can be added

然后:

my $instance = MyClass->new(attr => "foo");

say $instance->attr; # foo
$instance->attr("bar"); # here, we change the instance, but not the class
say $instance->attr; # bar

【讨论】:

    猜你喜欢
    • 2016-12-11
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2023-03-31
    相关资源
    最近更新 更多