两个 类 在 Java 中共享静态变量

Two classes sharing static variable in Java

我有两个 classes,class Place 和 class Game。这不是继承关系,但我希望我的游戏 class 有一个 Place 树状图,我的 Place class 也有一个树状图,但我希望两个树状图在同一事物中是一个,这样我就不会必须不断更新两者。

出现的另一个问题是由于我需要做的事情的性质,每当我在构造函数中创建一个 place 对象时,我需要立即将该对象放入树图中 places.put(id ,这个),问题是构造函数要求我初始化我的树图,但是如果我每次调用构造函数时都初始化它,显然我每次都会得到新的地图。

简而言之,我需要一种方法让两个 classes 共享同一个静态树图和 2. 只需初始化一次,这样我就不会重新初始化它。我正在考虑做一些时髦的事情,比如拥有一个布尔值 isSet 数据成员,但我不想走那条路。

public Place(Scanner fileInput, Report rep) {
    // this constructor will only read enough information for one
    // place object and stop on the line for which place it read
    name = "";
    description = "";

    // report object contains fields to initialize to help
    // validate the data. // see report class
    int idNumber; 
    int linesToRead; // number of lines to read for one place object
    while ( (fileInput.hasNextLine() ) && rep.placeInfoFound() == false  ) {
    //1. Call getline. getline has a while loop that will continue
    // until it reaches a line of data worth reading
    // first data we expect is the places line
    // after that, we will be on the 'PLACES line which will have
    // two fields, both place and id.
    //2 call ListToTokens which will make an arraylist of words
    // where each element is a token. token sub 1 is the number of
    // places.

        ArrayList<String> tokens = new ArrayList<String>();
        tokens = findPlaceInfo(fileInput, rep);
    }
    places = new TreeMap<Integer, Place>();
    places.put(id, this);
    //WE HAVE TO REINITIALIZE the fact that we found
    // place info back to false so that when we call again
    // we can run the while loop
    rep.assert_place_info_found(false);
} // function brace

private static TreeMap<Integer, Place>places;

您想使地图成为地点 class(或游戏 class,这无关紧要)的静态成员,如下所示:

import java.util.Map;
import java.util.TreeMap;

public class Place {
    //  Static Attributes
    private static final Map<Place, Object> places = new TreeMap<>();

    //  Constructors
    public Place(final Object key, final Place value) {
        places.put(key, value);
    }

    //  Methods - Static Getters
    public static Map<Place, Object> getPlaces() { return places; }
}

因此,从您的 'Game' class,您可以静态调用 Place::getPlaces 函数。如果您还没有创建 'Place' class,这将加载 class 并实例化静态对象。然后,如果您愿意,可以缓存该引用。

话虽这么说,但我建议不要将代码结构化为那样依赖静态,因为这种紧密耦合会导致更复杂的代码到处跳转。不过,如果不更好地了解您的项目及其要求,我无法提出更多建议,所以我将保留它。

祝你好运!