【发布时间】:2018-03-23 02:26:55
【问题描述】:
我正在编写最初使用静态对象来保存数据的代码。我意识到这是一种代码异味,并决定实现单例设计模式。
我有一个抛出 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;
}
}
【问题讨论】:
-
你能分享错误的堆栈跟踪吗,我不确定你从哪里得到 IOException
-
如果 IOException 真的抛出了这一行,则意味着
Inventory类有初始化问题 - 默认构造函数或一些静态类变量或实例变量初始化或 init 静态块执行一些 IO 操作。可以是在初始化期间读取属性文件之类的事情吗?看看 Inventory 类。我猜这是在类加载期间发生的静态变量初始化...... -
你能分享堆栈跟踪吗?
-
您是否收到“库存的非法修饰符;只允许最终版本”?
-
您的实现并不是真正的单例模式。这是一个只有静态成员的类。通常,您将在第一次访问时创建唯一的类实例。如果需要,您可以在那里捕获异常。寻找“java 单例模式同步”可能会有所帮助。您可以更改您的实现以使 DataStorage 类成为具有非静态成员的单例。
标签: java oop design-patterns singleton