Address Call Class

I have an abstract Moveable class with a method abstract void move()that extends with the Bullet class and the symbol of the abstract class , and the Symbol extends with the Survivor class and the Zombie class . In Survivor and Bullet, the method move()does not require any parameters, whereas in the Zombie class, the method move()depends on the actual position of the survivor. A survivor and several zombies are created in the Gui class .

I wanted to access the survivor in Zombie - what's the best way to do this? I wrote a method in GuigetSurvivor() , but I don’t see how to access this method in Zombie ?

I know that as a workaround, I could just pass the survivor [ Survivor ] as a parameter to move()and ignore it in Bullet and Survivor , but this is so ... bad practice.

+3
source share
5 answers

It depends on where your survivor is. Your zombie will need a link to Survivor somewhere - what is it for? Who should be responsible for providing this?

, Gui , , - GameState, , Gui . , , getSurvivor() Gui/Gamestate - Zombie, , , . GameState , .

: - :

public class Zombie
{
   private final Gui guiThatMadeMe;

   public Zombie(Gui owner)
   {
      guiThatMadeMe = owner;
   }

   ....

   public void move()
   {
      Survivor guy = guiThatMadeMe.getSurvivor();

      // Do whatever you need to with the survivor
   }
}


public class Gui
{
   private Survivor lonelyGuy;

   ... 

   public Survivor getSurvivor()
   {
      return lonelyGuy;
   }

   public void createNewGame() // I'm guessing you have some method like this
   {
       lonelyGuy = new Survivor();
       for (int i = 0; i < NUM_ZOMBIES; i++)
       {
          Zombie zombie = new Zombie(this); // pass in this reference
          // Do something with the zombie
       }
       // other setup
   }
}

, , , . , , . , , .

0

(-) , .

, , .detect(Survivor) Zombie. .follow(Survivor). Gui, , Survivor. Moveable .

, .

+2

Survivor, Singleton.

0

, , move() . Move , ,

move(Target t)

Target - , Zombie Survivor

move(Position p)

, , (Target, , , )

0
source

GameState @Andrzej Doyle's idea extension above ...

If all Zombies need a (potentially complex) Gui class, this is the position of Survivor, ask Gui to implement a simple interface with this method only, and Gui will hand over an instance of itself to Zombies when it builds them.

This makes Zombie more testable since only one method needs to be mocked.

interface GameState {
  Survivor getSurvivor();
}

class Zombie extends Character {
  public Zombie(GameState gs, ...) {
    this.gs = gs;
    ...
  }
  ...
}

class Gui implements GameState {
  ...
  private createZombie(...) {
    return new Zombie(this, ...);
  }
  ...
}
0
source

Source: https://habr.com/ru/post/1746357/


All Articles