我对Moose很新,并一直在努力遵循最佳实践。我知道我们应该尽可能地使类不可变。我的问题是,在构造对象之后,我们可以使用setter更改public属性的值,并且仍然使该类是不可变的吗?
答案 0 :(得分: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