读者容错模式是当从一个数据模型中读取数据的时候,无论这个数据模型如何变换,尽最大可能读取自己需要的数据,达到读取数据健壮性的要求。例如我们有一个数据模型类:RainbowFish,表示一种鱼。有一个读写数据的类:RainbowFishSerializer,来获取RainbowFish的name、age、lengthMeters、weightTons等数据。但是RainbowFish是第三方提供,可能在迭代升级的时候改变了类结构,例如增加了子类:RainbowFishV2,记录了更加详细的信息。数据结构发生了变化,我们在读取的时候就要进行适配,避免由于改变导致的crash。
代码:
/**
*
* RainbowFish is the initial schema
*
*/
public class RainbowFish implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private int lengthMeters;
private int weightTons;
/**
* Constructor
*/
public RainbowFish(String name, int age, int lengthMeters, int weightTons) {
this.name = name;
this.age = age;
this.lengthMeters = lengthMeters;
this.weightTons = weightTons;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getLengthMeters() {
return lengthMeters;
}
public int getWeightTons() {
return weightTons;
}
}
/**
*
* RainbowFishV2 is the evolved schema
*
*/
public class RainbowFishV2 extends RainbowFish {
private static final long serialVersionUID = 1L;
private boolean sleeping;
private boolean hungry;
private boolean angry;
public RainbowFishV2(String name, int age, int lengthMeters,