在Singleton设计模式上引发IOException

时间:2018-03-23 02:26:56

标签: java oop design-patterns singleton

我正在编写最初使用静态对象来保存数据的代码。我意识到这是一种代码味道,并决定实施Singleton设计模式。

我有一个抛出IOException的对象,当它被声明为类变量时我无法初始化它。我已附上以下代码。

谢谢

import java.import java.util.List;
import java.io.IOException;
import java.util.ArrayList;

public class DataStorage{
  private static List<Employee> empList = new ArrayList<Employee>();
  private static List<Manager> managerList = new ArrayList <Manager>();
  private static List<Dish> allDishes = new ArrayList<Dish>();
  private static List<Table> allTables = new ArrayList<Table>();
  private static Inventory inventory = new Inventory(); //Error is given in this line

  private DataStorage () {}

  public static List<Employee> getEmpList() {
      return empList;
  }

  public static List<Manager> getManagerList() {
      return managerList;
  }

    public static List<Dish> getAllDishes() {
        return allDishes;
    }

  public static List<Table> getAllTables() {
      return allTables;
  }

  public static Inventory getInventory() {
      return inventory;
  }

}

1 个答案:

答案 0 :(得分:0)

其中一个,您的帖子不包含Singleton - Singleton确保该类只有一个实例 - 而不是拥有所有这些static字段,可以是实例字段;因为只有一个Singleton的实例。最后,既然你提到你的Inventory构造函数可能抛出IOException,你可以懒惰地初始化该字段并用try-catch包装它。像,

public final class DataStorage {
    private List<Employee> empList = new ArrayList<Employee>();
    private List<Manager> managerList = new ArrayList<Manager>();
    private List<Dish> allDishes = new ArrayList<Dish>();
    private List<Table> allTables = new ArrayList<Table>();
    private Inventory inventory = null;

    private static DataStorage _instance = new DataStorage();

    public static DataStorage getInstance() {
        return _instance;
    }

    private DataStorage() {
    }

    public List<Employee> getEmpList() {
        return empList;
    }

    public List<Manager> getManagerList() {
        return managerList;
    }

    public List<Dish> getAllDishes() {
        return allDishes;
    }

    public List<Table> getAllTables() {
        return allTables;
    }

    public Inventory getInventory() {
        if (inventory == null) {
            try {
                inventory = new Inventory();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return inventory;
    }
}