如何从班级到私人会员获取信息?

时间:2021-07-27 22:51:45

I am writing a system that has several classes. There is one class that stores as a private field, an instance of another class. The second class needs to know information about the private fields in the first class. Can this be done?

我正在编写一个有几个类的系统。有一个类存储为私有字段,另一个类的实例存储。第二类需要知道第一类中私有字段的信息。可以这样做吗?

EDIT: I am trying to make a "house"; this includes rooms and people

编辑:我想做一个“房子”;这包括房间和人

The way I have it organized there is an instance of the People class in the Room class. However, the room number, which is stored in the room, needs to be known to each instance of People. So how do I get this information from Room? In a more broader sense, how could I get info from a private field in a class to an instance of another class stored as a private field in the class.

我组织它的方式是在Room类中有一个People类的实例。但是,每个People实例都需要知道存储在房间中的房间号。那么如何从Room获取此信息?从更广泛的意义上讲,我如何从类中的私有字段获取信息到另一个类的实例,该类存储为类中的私有字段。

1 个解决方案

#1


0  

In general, you want to structure your code so that objects do not know about their encapsulators to avoid spaghetti code and circular dependencies, so maybe you can reconsider your design. However, if a Room is to know about People and People to know about the Room they are in, then a straight forward way would be for code outside both of these objects to construct them:

通常,您希望构造代码,以便对象不知道其封装器以避免意大利面条代码和循环依赖,因此您可以重新考虑您的设计。但是,如果一个房间要了解人们和人们知道他们所在的房间,那么直接的方法是在这两个对象之外的代码构建它们:

public class House {
    private final Room room1;
    private final Room room2;

    public House() {
        Room room1 = new Room();
        Room room2 = new Room();

        People group1 = new People();
        People group2 = new People();

        group1.setRoom(room1);
        group2.setRoom(room2);

        this.room1 = room1;
        this.room2 = room2;
    }
}

public class People {
    private final Room room;

    public People(Room room) {
        this.room = room;
    }
}

#1


0  

In general, you want to structure your code so that objects do not know about their encapsulators to avoid spaghetti code and circular dependencies, so maybe you can reconsider your design. However, if a Room is to know about People and People to know about the Room they are in, then a straight forward way would be for code outside both of these objects to construct them:

通常,您希望构造代码,以便对象不知道其封装器以避免意大利面条代码和循环依赖,因此您可以重新考虑您的设计。但是,如果一个房间要了解人们和人们知道他们所在的房间,那么直接的方法是在这两个对象之外的代码构建它们:

public class House {
    private final Room room1;
    private final Room room2;

    public House() {
        Room room1 = new Room();
        Room room2 = new Room();

        People group1 = new People();
        People group2 = new People();

        group1.setRoom(room1);
        group2.setRoom(room2);

        this.room1 = room1;
        this.room2 = room2;
    }
}

public class People {
    private final Room room;

    public People(Room room) {
        this.room = room;
    }
}