繁体   English   中英

在Singleton设计模式上引发IOException

[英]Throws IOException on Singleton Design Pattern

我正在编写最初使用静态对象保存数据的代码。 我意识到这是一种代码味道,因此决定实施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;
  }

}

第一,您的帖子不包含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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM