一个类只能由外部环境使用它的属性是否可以接受? [关闭]

问题描述 投票:2回答:1

有时我们遇到一个类不需要使用自己的属性的问题。见方法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是一个tight-coupling结构,这意味着BallWorld都知道彼此,这是不好的。

那么,哪种方法更好?

  • 答:松散耦合,但有些类不会使用自己的属性,或者
  • B:类会使用它们的属性,但紧耦合结构?

什么时候使用?

c++ oop properties coupling tightly-coupled-code
1个回答
3
投票

A更好,因为它更具可扩展性。

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

所以是的,一个类只能由外部环境使用它的属性是可以接受的,因为这可能不是永远的情况。

也就是说,如果xy告诉你一些球的位置,那么那些更多的是关于一个类告诉你安装球实例的集合,而不是球本身的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.