我正在编写一个简单的游戏来学习更多的 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
(一个低级结构)必须是向用户呈现消息而不是“传递这个备份”的人,我觉得这不是优雅的,因为它结合了 location
至 UserInterface::*
.
你的意见?
最佳答案
所有的问题都可以通过增加一层间接来解决。我会使用您建议的变体,并通过允许 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/