0

免责声明 - 这是学校学期项目的一部分。

我们应该使用备忘录模式来保存对象状态。这个对象是 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)
4

1 回答 1

0

非静态内部类的实例具有对其外部类实例的隐藏引用。这意味着如果您要序列化内部类的实例,外部类的实例将与它一起被序列化。如果外部类不可序列化,您将获得一个java.io.NotSerializableException.

如果您不希望外部类的实例与内部类的实例一起序列化,请创建内部类static

public class Model {
   // ...
   public static class Memento implements Serializable {
       protected ModelData data;
       // ...
   }
}

内部类static没有对其外部类实例的引用。

于 2016-11-29T14:25:16.973 回答