免责声明 - 这是学校学期项目的一部分。
我们应该使用备忘录模式来保存对象状态。这个对象是 MVC 中的一个模型。所以我现在的方式是(简化的):
public class Model {
// ...
public static class Memento implements Serializable {
protected Stats stats;
public Memento(Stats stats) {
this.stats = stats;
}
}
public static class Stats implements Serializable {
protected int score;
protected int cannonPos;
protected int cannonAngle;
protected int cannonSpeed;
protected int totalShotsFired = 0;
protected int enemiesHit;
protected transient List<StatsObserver> observers = new ArrayList<StatsObserver>();
// + getters etc
}
}
我已经读过,出于合理的原因,在 Java 中实际上不可能有一个可序列化的内部类而外部类不是。但是,在我的情况下,当内部类是时,我不需要实例化外部类。内在根本不需要外在。它的结构只有这样,以便外部类可以访问内部的成员。
这就是我课程的纪念品描述中所说的:
......这也是有道理的。只有模型应该能够访问 Memento 中的详细信息。“看守人”对象(处理将数据保存到磁盘/从磁盘检索数据的对象)不应在对象内部看到。由于Java没有友元类,这应该是要走的路。
这是否意味着为了按照建议实施它,我不能使用序列化?
编辑:
我将 Memento 类和 Stats 类设为静态,但仍然出现错误。好像还是有this
参考的Model.Stats
java.io.NotSerializableException: cz.melkamar.adp.shooter.model.Model
- field (class "cz.melkamar.adp.shooter.model.Model$Stats", name: "this$0", type: "class cz.melkamar.adp.shooter.model.Model")
- object (class "cz.melkamar.adp.shooter.model.Model$Stats", cz.melkamar.adp.shooter.model.Model$Stats@de1a1b8)
- field (class "cz.melkamar.adp.shooter.model.Model$Memento", name: "stats", type: "class cz.melkamar.adp.shooter.model.Model$Stats")
- root object (class "cz.melkamar.adp.shooter.model.Model$Memento", cz.melkamar.adp.shooter.model.Model$Memento@1e920c72)