天天看點

使用者枚舉來實作單例模式

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

 

public enum EnumSingleton implements Serializable {

 

      INSTANCE;

      private String book = null;

 

      public String getBook() {

            return book;

      }

 

      public void setBook(String book) {

            this.book = book;

      }

 

      public void doSomething() {

      };

}

 

class EnumSingletonSerialization {

      public static void main(String[] args) {

            File file = new File("singleton");

            ObjectOutputStream oos = null;

            ObjectInputStream ois = null;

            try {

                  oos = new ObjectOutputStream(new FileOutputStream(file));

                  EnumSingleton singleton = EnumSingleton.INSTANCE;

                  singleton.setBook("HelloWorld");

                  oos.writeObject(EnumSingleton.INSTANCE);

                  System.out.println(EnumSingleton.INSTANCE);

                  oos.close();

                  ois = new ObjectInputStream(new FileInputStream(file));

                  EnumSingleton singleton2 = (EnumSingleton) ois.readObject();

                  System.out.println(singleton2.getBook());

                  System.out.println(singleton == singleton2);

            } catch (FileNotFoundException e) {

                  e.printStackTrace();

            } catch (IOException e) {

                  e.printStackTrace();

            } catch (ClassNotFoundException e) {

                  e.printStackTrace();

            } finally {

                  if (oos != null) {

                        try {

                              oos.close();

                        } catch (IOException e) {

                              e.printStackTrace();

                        }

                  }

                  if (ois != null) {

                        try {

                              ois.close();

                        } catch (IOException e) {

                              e.printStackTrace();

                        }

                  }

            }

      }

}