クラスが独自のプロパティを使用する必要がないという問題に遭遇することがあります。アプローチ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 は密結合構造であり、と がお互いBall
をWorld
知っていることを意味し、これは良くありません。
それで、どちらがより良いアプローチですか?
- A : 疎結合ですが、一部のクラスは独自のプロパティを使用しません。または
- B : クラスはそのプロパティを使用しますが、密結合構造ですか?
それぞれをいつ使用するのですか?