Disclaimer - this is a part of a school semester project.
We should be using Memento pattern to save an object state. This object is a model in MVC. So the way I have it now is (simplified):
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
}
}
I have read that having a Serializable inner class whilst the outer class is not is not really possible in Java for reasonable reasons. BUT, in my case I do not need the outer class to be instantiated when the inner one is. Inner does not need outer at all. It is only structured like this so that the outer class can access the inner's members.
This is what my course's Memento description says:
... and that makes sense as well. Only the Model should be able to access the details inside Memento. The "Caretaker" object (an object handling saving/retrieving the data to/from disk) should not see inside the object. Since Java does not have friend classes, this should be the way to go.
Does it mean that in order to implement it as suggested I cannot use Serialization?
Edit:
I made Memento class static, as well as Stats class, but I am still getting the error. It seems that there still is a this
reference in 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)