当程序状态不断变化时,不可变对象的有用性 [英] Usefulness of immutable objects when the state of a program constantly changes

查看:97
本文介绍了当程序状态不断变化时,不可变对象的有用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道不可变对象总是具有相同的状态,即实际创建它们的状态。它们的不变量是由构造函数建立的,因为它们的状态在构造之后不会改变,所以这些不变量总是保持良好状态,这就是为什么它们在多线程环境中发布是安全的。这一切都很好但是因为我们生活在一个动态的世界中,程序的状态不断变化,如果我们通过不可变对象构造程序的状态,这些对象会给我们带来什么好处?

I know that immutable objects always have the same state, the state in which they are actually created. Their invariants are establised by the constructor and since their state does not change after construction , those invariants always hold good and this is why they are safe to publish in a multi threaded environment. This is all fine but since we live in a dynamic world , where the state of program changes continuously , what benefits do such objects give us if we construct the state of our program through immutable objects?

推荐答案

这些对象给我们带来了什么好处你已经回答过了。

"what benefits do such objects give us" you already answered that.

关于动态部分你的问题,如果你需要改变一个不可变对象,你可以用旧的对象创建一个新对象:

Regarding the "dynamic" part of your question, if you need to "change" an immutable object, you can create a new one from the old one:

Immutable oldObj = new Immutable(...);
Immutable newObj = new Immutable(oldObj.property1, "a new value for property 2");

如果你发现你一直这样做,那么你可能需要让对象变为可变并添加能够在并发环境中使用该对象所需的相关踏板安全功能。

If you find that you keep doing that repeatedly, then maybe you need to make the object mutable and add the relevant tread-safety features that are needed to be able to use that object in a concurrent environment.

这篇关于当程序状态不断变化时,不可变对象的有用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆