空对象模式:使用对象继承来实现程序中的空判断
优点:增加程序可读性
空对象接口:
public interface NullObject {
boolean isNull();
}
原对象:
public class Subject implements NullObject{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean isNull() {
return false;
}
}
创建原对象的空对象:
public class NullSubject extends Subject{
@Override
public boolean isNull() {
return true;
}
}
场景调用:
public class Client {
public static void main(String[] args) {
Subject subject = findSubject();
if(subject.isNull()){
System.out.println("对象为空");
}else{
System.out.println("对象不为空");
}
}
static Subject findSubject(){
Random random = new Random();
int type = random.nextInt(2);
if(type == 0){
return new NullSubject();
}else{
return new Subject();
}
}
}