一个班级可以接受仅由外部环境使用其属性

Is it acceptable for a class to have its properties used ONLY by the outside environment?

本文关键字:外部环境 属性 一个      更新时间:2023-10-16

有时我们会遇到一个问题不需要使用自己的属性。请参阅方法 A:

struct Ball {
    double mass = 1;
    double x = 0;
    double y = 0;
};
struct World {
    std::vector<Ball*> balls;
    void run_physics() {
        // here we run the physics
        // we can access every ball and their x, y properties
    }
};

为了避免这种情况,我们可以使用方法 b

struct World;
struct Ball {
    World* world = NULL;
    double mass = 1;
    double x = 0;
    double y = 0;
    void run_physics() {
        if (this->world != NULL) {
            // here we run the physics again
            // we can access every other ball properties through this->world->balls vector.
        }
    }
};
struct World {
    std::vector<Ball*> balls;
};

但是接近B是一个紧密的耦合结构,这意味着BallWorld彼此都不好,这不好。

那么,哪个更好的方法?

  • a :松散耦合,但是有些类不会使用自己的属性,或者
  • b :类将使用其属性,但是紧密耦合结构?

什么时候使用每个?

a 更好,因为它更可扩展

球可能具有与当前计算无关的其他属性,例如用于计算惯性矩的成员(例如,如果是空心球(。

是的,是的,可以接受仅由外部环境使用其属性,因为可能永远不会发生这种情况。

也就是说,如果xy告诉您有关球的位置的信息,那么这些与一堂课有关,告诉您有关已安装的球实例的收集,而不是成为球本身的一部分。