在java中,我们更喜欢null object
模式,而不是在所有引用中进行非空检查而使代码变得困惑。最近,我们遇到了通过保留 singleton
对象来使用 null 对象
的问题。
假设我们有如下的 Person
类
public class Person {
public String firstName;
public String lastName;
public boolean isNull() {
return false;
}
public static final Person NULL = new Person() {
public boolean isNull() { return true; }
}
}
在这种情况下,虽然我已将 NULL
对象声明为 Final,但我仍然可以修改成员变量及其全局可用。
Person nullRef = Person.NULL;
Person.NULL.firstName = "sample";
System.out.println(nullRef.firstName);
在本例中,它只有三个字段,我可以通过重写这三个 getter 方法来解决可变性问题。但实际上,有很多字段很难覆盖所有相应的 getter 方法。
是否有任何标准模式或策略来解决 NULL
对象中的这种可变性问题?
最佳答案
使用 Google Guava 库中的可选内容
Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
引用库文档:
Besides the increase in readability that comes from giving null a name, the biggest advantage of Optional is its idiot-proof-ness
这是处理空对象的更自然的方式
关于java - 使空对象不可变的任何标准模式或策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13681246/