简体   繁体   中英

Hierarchy classes dependency

I want some advice about class designs. Let's say that I have 3 classes, "class A", "class B" and "class C" . Each class has different namespaces. "A" has an instance of "B", and "B" has an instance of "C" . Each class have a "struct Setting" and each class is set with a SetSettings(). Actually, "A" uses "B" to do its job, and "B" uses "C" to do its job .

My question is, is there any better way to do these hierarchy settings?

For example, to break the relation between "A" and "C", "B" could have the same parameters of "C::Settings" instead of defining a c_settings...

Thanks in advance!

Ah

#include "B.h"
namespace A {
struct Settings {
  int param_for_A_1;
  B::Settings b_settings;
};
class A {
  void SetSettings(const Settings& source) {
    settings_ = source;
    b_.SetSettings(source.b_settings);
  }
  Settings settings_;
  B::B b_;
};
}

Bh

#include "C.h"
namespace B {
struct Settings {
  int param_for_B_1;
  int param_for_A_2;
  C::Settings c_settings;
};
class B {
  void SetSettings(const Settings& source) {
    settings_ = source;
    c_.SetSettings(source.c_settings);
  }
  Settings settings_;
  C::C c_;
};
}

Ch

namespace C {
struct Settings {
  int param_for_C_1;
};
class C {
  void SetSettings(const Settings& source) {
    settings_ = source;
  }
  Settings settings_;
};
}    

main.cpp

#include "A.h"
int main() {
  A::Settings settings;
  // Hierarchy settings...
  settings.param_for_A_1 = 1;
  settings.b_settings.param_for_B_1= 2;
  settings.b_settings.param_for_B_2 = 3;
  settings.b_settings.c_settings.param_for_C_1= 4;
  class A::A a;
  a_.SetSettings(settings);
  return;
}

As of now, you are not indeed using inheritance, but rather composition. Composition means that a class has an attribute of the type of another class, rather than inheriting the functions and attributes of a parent class.

If I wanted to use inheritance, I probably would have used the class C as a base from which B would inherit. A would then inherit from B. Each "generation" having their own int attribute corresponding to their "settings".

Depending on the situation, this might be more appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM