Memento 备忘录

Memento 备忘录

  • 记录状态便于回滚
  • 记录对象的某一个瞬间(快照)
  • 序列化与反序列化

    1. public class Memento {
    2. public static void main(String[] args) {
    3. Test test = new Test(1,2,"测试");
    4. File file = new File("d:/LZY/test.data");
    5. ObjectOutputStream objectOutputStream = null;
    6. ObjectInputStream objectInputStream = null;
    7. try {
    8. objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
    9. objectInputStream = new ObjectInputStream(new FileInputStream(file));
    10. objectOutputStream.writeObject(test);
    11. Test test1 = (Test) objectInputStream.readObject();
    12. System.out.println(test1.toString());
    13. } catch (IOException e) {
    14. e.printStackTrace();
    15. } catch (ClassNotFoundException e) {
    16. e.printStackTrace();
    17. } finally{
    18. if(objectOutputStream!=null){
    19. try {
    20. objectOutputStream.close();
    21. } catch (IOException e) {
    22. e.printStackTrace();
    23. }
    24. }
    25. if (objectInputStream !=null){
    26. try {
    27. objectInputStream.close();
    28. } catch (IOException e) {
    29. e.printStackTrace();
    30. }
    31. }
    32. }
    33. }
    34. }
    35. class Test implements Serializable {
    36. int a;
    37. int b;
    38. String str;
    39. public Test(int a, int b, String str) {
    40. this.a = a;
    41. this.b = b;
    42. this.str = str;
    43. }
    44. public String toString(){
    45. return "a:"+a+" b:"+b+" str:"+str;
    46. }
    47. }