有时我们遇到一个类不需要使用自己的属性的问题。见方法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结构,这意味着Ball
和World
都知道彼此,这是不好的。
那么,哪种方法更好?
什么时候使用?
A更好,因为它更具可扩展性。
球可能具有与当前计算无关的其他属性,例如用于计算惯性矩的构件(例如,如果是空心球)。
所以是的,一个类只能由外部环境使用它的属性是可以接受的,因为这可能不是永远的情况。
也就是说,如果x
和y
告诉你一些球的位置,那么那些更多的是关于一个类告诉你安装球实例的集合,而不是球本身的一部分。