c++ - 多态值得增加耦合吗?

标签 c++ polymorphism coupling

我正在编写一个简单的游戏来学习更多的 C++ 经验,我有一个想法,我觉得多态性几乎有效,但没有。在这个游戏中,Party通过 Map 相当线性地移动, 但偶尔会遇到 Fork在路上。 fork (基本上)是一个 std::vector<location*> . 最初我打算将类似以下内容的代码写入 a Party成员函数:

if(!CurrLocation->fork_.empty())
   // Loop through forks and show options to the player, go where s/he wants
else
  (CurrLocation++)

但我想知道以下的某些变体是否会更好:

CurrLocation = CurrLocation->getNext();

Fork 实际上是从 Location 派生的,并重载了一些新函数 getNext() .但在后一种情况下,location (一个低级结构)必须是向用户呈现消息而不是“传递这个备份”的人,我觉得这不是优雅的,因为它结合了 locationUserInterface::* .

你的意见?

最佳答案

所有的问题都可以通过增加一层间接来解决。我会使用您建议的变体,并通过允许 getNext 接受解决方向选择的对象来将 Location 与 Party 分离。这是一个示例(未经测试):

class Location; 

class IDirectionChooser
{
public:
  virtual bool ShouldIGoThisWay(Location & way) = 0;
};

class Location
{
public:
  virtual Location * GetNext(IDirectionChooser & chooser)
  {
    return nextLocation;
  }

  virtual Describe();
private:
  Location * nextLocation;
};

class Fork : public Location
{
public:
  virtual Location * GetNext(IDirectionChooser & chooser)
  {
    for (int i = 0; i < locations.size(); i++)
      if (chooser.ShouldIGoThisWay(*locations[i]))
        return locations[i];
  }
  virtual Describe();
private:
  vector<Location *> locations;
};

class Party : public IDirectionChooser
{
public:
  void Move()
  {
    currentLocation = currentLocation->GetNext(GetDirectionChooser());
  }

  virtual IDirectionChooser & GetDirectionChooser() { return *this; }

  virtual bool ShouldIGoThisWay(Location & way)
  {
    way.Describe();
    cout << "Do you want to go that way? y/n" << endl;

    char ans;
    cin >> ans;
    return ans == 'y';
  }
};

关于c++ - 多态值得增加耦合吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/426162/

相关文章:

c++ - C++ Windows/Mac/iOS 中的西类牙字符

c++ - 为什么要在 catch block 中使用 "const"?

c++ - 使用基对象修改/访问派生类信息的问题设计

oop - MATLAB和全局变量的使用?

ajax - 在 mvc 中,将表单(什么 Controller )的 ajax 脚本放在哪里?

c++ - 我怎样才能捕捉到 Qt 中子 Widget 的变化?

c++ - 在类构造函数中初始化常量 vector (C++)

c++ - 如何在不相关的类型上实现动态多态性(运行时调用调度)?

c++ - 带有模板叶类的奇怪的重复模板

java - 通过松耦合或高耦合来改进我的代码(如果有的话)?