przejściowy dla serializacji singletonu
Efektywna Java - Aby zachować gwarancję singletonu, musisz zadeklarować wszystkie pola instancji jako przejściowe i podać metodę „readResolve”. Co osiągamy, deklarując tutaj pola przejściowe? Oto próbka:
....
....
public final class MySingleton implements Serializable{
private int state;
private MySingleton() { state =15; }
private static final MySingleton INSTANCE = new MySingleton();
public static MySingleton getInstance() { return INSTANCE; }
public int getState(){return state;}
public void setState(int val){state=val;}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
public static void main(String[] args) {
MySingleton c = null;
try {
c=MySingleton.getInstance();
c.setState(25);
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (MySingleton) ois.readObject();
ois.close();
System.out.println("after deser: contained data is " + c.getState());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Niezależnie od tego, czy deklaruję zmienną „state” jako przejściową, czy nie, otrzymuję c.getState () gettign wydrukowane jako 25. Am I Missing something here?