问题:当只有类型很重要时如何存储字段。
描述:我简化了问题描述以突出问题。该类Dragon
有一个行为,Roar
,它被存储为一个成员变量。ARoar
通常没有状态,也不需要保存。但是,Dragon
需要知道Roar
它在重新创建时具有什么特定类型。
@Entity
public class Dragon implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private double height;
private Roar roar;
public String roar() {
return roar.roar();
}
}
public interface Roar {
String roar();
}
public class QuietRoar implements Roar {
public String roar() {
return "grr.."; // In real scenario, lots of logic occurs here.
}
public class LoudRoar implements Roar {
public String roar() {
return "AHHHGRRRR"; // More logic here.
}
可能的解决方案:
使roar
字段瞬态并存储一个额外的类型字段,该字段Class
包含该roar
字段的类类型。然后Dragon
类变成:
@Entity
public class Dragon implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private double height;
@Transient
private Roar roar;
private Class<? extends Roar> roarType;
public void setRoar(Roar roar) {
this.roar = roar;
roarType = roar.getClass();
}
public String roar() {
if(roar == null) {
try {
roar = roarType.newInstance();
} catch (InstantiationException | IllegalAccessException ex ) {
// oo ohh..
}
}
return roar.roar();
}
}