Do getters violate the Law of Demeter?

Suppose there is a type GameStatethat uses GameContext(via a method process):

abstract class GameState {
    public abstract void process(GameContext context);
}

GameContext will contain such things as Player, Shops, ect .. things that are necessary for the game.

The state will gain access to what it needs:

class CombatState extends GameState {
    public void process(GameContext context) {
        Player player = context.getPlayer();

        if(player.isAlive()) {
            //...
        }
    }
}

The statement player.isAlive()can be rewritten as context.getPlayer().isAlive().

My question

Demeter’s law states that objects should only interact with immediate relatives. Will this be a violation of the principle and how will it be resolved?

, , . , , , , " ". , , a ShopState , a CombatState

+4
2

, - . - , - .

process .

:

class CombatProcess extends GameProcess {
    public void hit(Player puncher, Player beaten) {
        if (beaten.getState().isAlive()) {
           Weapon oneWeapon = one.getCurrentWeapon();
               ...
        }
    }
}

CombatProcess , .

, , CombatProcess! CombatProcess , .

EDIT:

:

, , ,

. Hook/Anchor-Pattern - 1996 - ( ). , 10 OOD - . :

... , .

, Hook/Ancher-Pattern 1996 CDI (spring ) .

-! :

  • .
  • Hook/Ancher-Pattern.
  • , .
+4

Loose Coupling.

, :

, (). java, , .

/ .

:

A, B, C.

B , A, C B.

A C , Loose Coupling.

, , .

0

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


All Articles