从单独的类获取对象的引用

时间:2019-12-01 00:05:44

标签: java oop

当前,有3个类互不继承。每个类都具有一个属性,该属性引用另一个类的实例,如下所示。

import java.util.ArrayList;

class Region {
    private Directory areaDirectory;

    public Region() {
        areaDirectory = new Directory();
    }

    public Directory getAreaDirectory() {
        return areaDirectory;
    }

    public void setAreaDirectory(Directory areaDirectory) {
        this.areaDirectory = areaDirectory;
    }
}

class Directory {
    private ArrayList<Area> areaList;

    public Directory() {
        areaList = new ArrayList<>();
    }

    public ArrayList<Area> getAreaList() {
        return areaList;
    }

    public void setAreaList(ArrayList<Area> areaList) {
        this.areaList = areaList;
    }

    public Area addNewArea(){
        Area area = new Area();
        return area;
    }
}

class Area {
    private String Name;

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public Region getAreaRegion() {
        // This returns a new region but need the region it was created in
        return new Region();
    }
}


public class Scratch {
    public static void main(String args[]) {
        Region r = new Region();
        Area a = r.getAreaDirectory().addNewArea();
        a.setName("Demo");

        //See getAreaRegion() method in Area class
        System.out.println(a.getAreaRegion());
    }
}

如何实现类似getAreaRegion()的方法,使其返回区域对象r?在此示例中如何设置继承以获取父对象?

1 个答案:

答案 0 :(得分:2)

我已经理解了您想用以下代码描述的业务逻辑:

有一个地区。每个区域都有一个目录。每个目录都有一个区域。 在这种情况下,我认为:

  • Region类持有对Directory字段的引用;
  • Directory类也有其自己的Region的引用;
  • 目录类保留对Area字段的引用;
  • Area类还为其自己的目录提供了引用。

然后我们可以通过以下方式创建类:

1.Region类

public class Region {
private Directory directory;

public Directory getDirectory() {
    return directory;
}

public void setDirectory(Directory directory) {
    this.directory = directory;
}
}

2.Directory类

class Directory{
private Region region;
private Area area;

public Region getRegion() {
    return region;
}

public void setRegion(Region region) {
    this.region = region;
}

public Area getArea() {
    return area;
}

public void setArea(Area area) {
    this.area = area;
}
}

3.Area class

class Area{
private Directory directory;
private String Name;

public Directory getDirectory() {
    return directory;
}

public void setDirectory(Directory directory) {
    this.directory = directory;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}
}

所以我们可以得到如下区域的区域:

area.getDirectory().getRegion();

我认为这更好,更简单地显示了业务逻辑。希望对某人有帮助:)