Imagine there was a GameState
type which uses a GameContext
(via a process
method):
abstract class GameState {
public abstract void process(GameContext context);
}
GameContext would contain things such as the Player, Shops, ect.. things that are essential to the game.
A state would access what it needed:
class CombatState extends GameState {
public void process(GameContext context) {
Player player = context.getPlayer();
if(player.isAlive()) {
//...
}
}
}
The statement player.isAlive()
could be rewritten as context.getPlayer().isAlive()
.
My Question
The Law of Demeter states that objects should only interact with direct relatives. Would this be a violation of the principle, and how would it be resolved?
For each state to be handled dynamically, the formal parameters must be acceptable by all possible states. This makes it hard to pass the object strictly what it needs, which is why each state grabs what it needs from a "main source". I feel that main source has very low cohesion, since a ShopState
would require different data than a CombatState