簡體   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