Is polymorphism an increase in adhesion?

I am writing a simplified game to learn how to get more experience in C ++, and I have an idea when I feel that polymorphism almost works, but not. In this game, it Partymoves rather linearly through a Map, but sometimes it can collide with Forkon the road. Plug (mainly) a std::vector<location*>. Initially, I was going to introduce into the function a Partysomething like the following:

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

But I was wondering if there could be several options for the following:

CurrLocation = CurrLocation->getNext();

With a fork actually derived from a location, and overloading some new feature getNext(). But in the latter case location(the low-level structure) should be the one that presents the message to the user instead of “transmitting this backup”, which I don’t feel is elegant as it connects locationup to UserInterface::*.

Your opinion?

+5
source share
4 answers

All problems can be solved by adding a level of indirection. I would use your proposed option and separate the location from the party, allowing getNext to accept an object that allows the choice of direction. Here is an example (untested):

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';
  }
};
+6
source

, . , . , , .

.

+1

, , , , , .

:

  • , , .
  • - , . , , , .
  • , .
+1

, , .

, , .

, , UserInterface?

, UserInterface Location, LocationViewAdapter?

0

All Articles