簡體   English   中英

為了訪問Java中其他地方的數據,我應該在哪里放置它?

[英]In order to access data elsewhere in java, where should I place it?

我想將文件中的數據放入變量中,然后可以在其他位置(其他類)中方便地訪問它。 我知道file path並將其讀取到變量。 然后我將它放在一個類中。 數據將不會更改只有一個副本。

// store data in a static field
public class MyContainer {
  private static Map<String, MyClass> data;
  public static void setData(Map<String, MyClass> data) {
    this.data = data;
  }
  public static Map<String, MyClass> getData(){
    return data;
  }
}

// set data at one place
Map<String, MyClass> data = new HashMap<>();
MyContainer.setData(data);

// access data at other places
MyContainer.getData(data);

盡管上面的代碼可以實現此目的,但我認為這很不好,因為我可以在為其分配數據之前對其進行訪問。
如何正確實施?

如果數據永不更改,請在構造函數中進行設置,然后刪除設置器。 還擺脫了static關鍵字。

public class MyContainer {
    private final Map<String, MyClass> data = new HashMap<>();
    public MyContainer(@Nonnull Map<String, MyClass> data) {
        this.data.putAll(data);
    }
    public Map<String, MyClass> getData(){
        return data;
    }
}

您可能想要返回Collections.unmodifiableMap(data); ,因此無法從外部修改data

使用吸氣劑方法。 如果您擔心某個類在准備好之前嘗試訪問它,請在getter中進行處理。

private boolean allowAccess; // set this to true once you're happy that the data is ready to read
public Map<String, MyClass> getData() {
  if (!allowAccess) {
    throw new IllegalStateException();
  }
  return data;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM