Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
以下规则定义了用于创建不可变对象的简单策略。并非所有记录为“不可变”的类都遵循这些规则。这并不一定意味着这些类的创造者是草率的 他们可能有充分的理由相信他们类的实例在构造后永远不会更改。但是,这种策略需要复杂的分析,不适合初学者。
final 和 private。final。更复杂的方法是使构造函数 private 并在工厂方法中构造实例。将此策略应用于 SynchronizedRGB 会导致以下步骤:
set,任意转换对象,并且在类的不可变版本中不应该存在。第二个,invert,可以通过让它创建一个新对象而不是修改现有对象来进行调整。private;他们进一步被限定为 final。final。完成这些更改后,我们有 :ImmutableRGB
final public class ImmutableRGB {
// Values must be between 0 and 255.
final private int red;
final private int green;
final private int blue;
final private String name;
private void check(int red,
int green,
int blue) {
if (red < 0 || red > 255
|| green < 0 || green > 255
|| blue < 0 || blue > 255) {
throw new IllegalArgumentException();
}
}
public ImmutableRGB(int red,
int green,
int blue,
String name) {
check(red, green, blue);
this.red = red;
this.green = green;
this.blue = blue;
this.name = name;
}
public int getRGB() {
return ((red << 16) | (green << 8) | blue);
}
public String getName() {
return name;
}
public ImmutableRGB invert() {
return new ImmutableRGB(255 - red,
255 - green,
255 - blue,
"Inverse of " + name);
}
}