0

请检查下面代码的第 5 行。如果有问题,请更正我的问题。

public class Location {
        private final Map<String, Integer> exits;
        public Location(Map<String, Integer> exits) {
            if(exits != null) {
                this.exits = new HashMap<String, Integer>(exits);
            } else {
                this.exits = new HashMap<String, Integer>();
            }
        }
}
4

1 回答 1

1

这个想法是封装地图,只允许通过Location类接口中指定的方式访问数据。

Location对象的创建者和Location类(或它可以实现的某些接口)的用户通常是系统中的两个不同组件。通过执行您显示为代码片段的内容,创建者将数据(地图)封装在类型对象中,Location以便用户只能用它做一些事情(例如location.calculateDistance())但不能做location.exits.remove('Colorado').

于 2020-10-07T05:43:39.307 回答