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

时间:2018-10-02 03:12:25

标签: java static treemap

我有两个班级,地方班级和游戏班。这不是继承关系,但是我希望我的Game类具有一个Place树形图,而我的Place类也具有一个树形图,但是我希望两个树形图在同一事物中成为一个,这样就不必不断更新两者。

出现的另一个问题是由于我需要执行的操作,每当我在构造函数中创建place对象时,都需要立即使用places.put(id,this)将对象放入树形图中,问题是构造函数要求我初始化树形图,但是如果每次调用构造函数时都对其进行初始化,显然每次都会得到新的映射。

简而言之,我需要一种让两个类共享同一静态树图的方法,并且只需对其进行一次初始化,这样就不会重新初始化它了。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;

1 个答案:

答案 0 :(得分:1)

您要使地图成为Place类(或Game类,无论哪一个)的静态成员,如下所示:

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; }
}

因此,从“游戏”类中,您可以静态调用Place :: getPlaces函数。如果尚未创建“ Place”类,则将加载该类并实例化静态对象。然后,您可以缓存该引用。

话虽这么说,我建议不要将代码构造为像这样依赖静态变量,因为紧密的耦合会导致更复杂的代码无处不在。不过,在不更好地了解您的项目及其需求的情况下,我无法提出太多建议,因此我将保留该建议。

祝你好运!