Brian goetz explains some of the benefits of immutability and some guidelines for constructing immutable classes 中,briangoetz说明了不变性的一些长处和构造不变类的一些准则。
When writing a class, it is always worthwhile to ask yourself whether this class could be effectively implemented as an immutable class 在编写类时,问问自己这个类是否可以作为不变类有效地实现,总是值得的。
You can often avoid creating duplicate objects by using static factory methods in preference to constructors on immutable classes that provide both 对于同时提供了静态工厂方法和构造函数的非可变类,通常可以用静态工厂方法而不是构造函数来避免创建重复的对象。
Depending on your application, even abstract types that contain many discrete values-such as vectors or matrices-might be good candidates for implementing as immutable classes 甚至包含许多离散值的抽象类型(如向量或矩阵)也很适合实现为不变类,这取决于您的应用程序。
Constant data are obvious candidates for immutability, and objects with complex and frequently changing states are generally inappropriate candidates for implementation with immutable classes 常量数据显然符合不变性,而状态复杂且频繁更改的对象通常不适合用不变类来实现。
immutable classes are very useful for simplifying the design of object-oriented programs-immutable objects require less defensive coding and offer relaxed synchronization requirements 不变类对于简化面向对象程序的设计非常有用不变的对象只需要较少的防御性编码,并且不要求严格的同步。
Keyword was included in the java language to assist developers in creating immutable classes, and enable compilers and runtime environments to optimize on the basis of declared immutability 关键字是为了帮助开发人员创建不可变类,并允许编译器和运行时环境以声明的不可变性为基础进行优化。