Context:
继续写看Oracle官方文档的笔记,这一章的内容是点击打开链接
1.前一章说,我们总是因怕生成对象的开销,避免使用不可变对象 immutable object。而是用改变对象的状态,这种方式。不过呢!随着垃圾回收机制,和对synchronized的省略,不可变对象也变的更加可行。
呵呵!对于我这种新手,以前还真没考虑synchronize这种事情,所以才不用immutable object吧。
策略strategy:
1.不要提供“setter”方法(修改字段、字段引用到的对象的方法)
2.将所有字段设置为private、final
3.将类修饰为final,不允许被继承、重写。
将构造方法修饰为final,提供工厂方法来构造实例。
4.如果字段引用到了可变对象,不允许这些对象发生改变
a)不提供修改可变对象的方法
b)不同享对可变对象的引用。不存储通过构造方法传进来的可变对象、额外对象的引用。
对于外部可对象:
如果需要的话,创建可变对象的副本来保持可变对象的引用。
内部可变的对象
同样复制对象,来避免在你的方法中返回原来的对象(可能已经被修改了)。
例子:
更改前:
public class SynchronizedRGB {
// Values must be between 0 and 255.
private int red;
private int green;
private int blue;
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 SynchronizedRGB(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 void set(int red,
int green,
int blue,
String name) {
check(red, green, blue);
synchronized (this) {
this.red = red;
this.green = green;
this.blue = blue;
this.name = name;
}
}
public synchronized int getRGB() {
return ((red << 16) | (green << 8) | blue);
}
public synchronized String getName() {
return name;
}
public synchronized void invert() {
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
name = "Inverse of " + name;
}
}
更改后:
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);
}
}
总结:
可看到Immutable Object的好处是省略了一堆的synchronized方法、逻辑。而又具有线程安全性。nice 哈