【问题标题】:class interaction design课堂交互设计
【发布时间】:2010-10-20 23:34:23
【问题描述】:

假设我有类似这样的编码

class Normal_Mode;
class Fast_Mode;
class File_Control; //handles all operations with reading/writing in file
class Main_Control {
 private:
 some_class *root; //all other classes need access to root pointer since there is all the data(binary tree)
 File_Control *c_file_control;
 Fast_Mode *c_fast_mode;
...
}

Main_Control::Main_Control ( int argc, char* argv[]) {
  ...
  if ( argc > 1 ) {
   c_fast_mode = new Fast_Mode(argc, argv[]);
  } else {
   c_normal_mode = new Normal_Mode();
  };
  ...
};

int main (int argc, char* argv[]) {
 Main_Control c_main_control(argc,argv);
 return 0;
}

假设用户输入的 argc > 1,我很高兴在 Fast_Mode 类中处理用户输入的内容,但是当我完成并想要在 Fast_Mode 下将内容写入文件或从文件中读取内容时。 现实世界中的人如何访问 File_control 类?

他们是否使一些全局数组充满了指向这些只需要 1 个实例的类的指针。

他们是否将指针传递给 Fast_Mode 和其他类,以便可以将其存储在私有成员中以供访问。

或者他们一直在构造/销毁这些类,具体取决于何时需要。

他们如何处理存储所有实际数据并且许多其他类需要访问它的 *root 指针

或者我的设计理念完全错误,现实世界中的人们会以其他方式这样做?

【问题讨论】:

    标签: c++ class class-design


    【解决方案1】:

    我真的不知道你想用这个实现什么:如果可能的话,让你的目标更清晰,但我想说的是人们通常会创建一个名为“Mode”的抽象接口,然后同时拥有 Normal_Mode 和 Fast_Mode实施它。这样你就可以编写以下代码:

    class Main_Control {
        private:
           some_class *root; //all other classes need access to root pointer since there is all the data(binary tree)
           File_Control *c_file_control;
           Mode *c_mode;
           ...
    };
    

    然后你可以这样设置:

    if ( argc > 1 ) {
       c_mode = new Fast_Mode(argc, argv[]);
    } else {
       c_mode = new Normal_Mode();
    };
    

    因此,您只需将常用函数放在 Mode 接口中,以便它们的行为方式相同,但可以放在相同的 mode 变量中。要了解有关class inheritance and polymorphism look here 的更多信息。我希望这能回答你的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多