【问题标题】:Throws IOException on Singleton Design Pattern在单例设计模式上引发 IOException
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-10-12
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多