首页 > 解决方案 > In Java, what's the best way to make class A do something when an event happens in class B without class B knowing of class A's existence?

问题描述

I'm making a little game and I have a PlayScreen, which has a GameWorld, which has a Player. Now whenever Player touches a teleport block, I dim the PlayScreen, then Player teleports and then the PlayScreen brightens back up again.

Currently to achieve this I added a boolean inTeleportAnimation to Player. Then PlayScreen checks every single frame inside update() if Player is in teleport animation and if so, it starts dimming the screen. Now this seems fine because it only checks for 1 boolean/trigger. But later there might be A LOT of different triggers for the PlayScreen to do something (e.g. dim the screen). It's probably a bad idea to have playScreen.update() check for every single trigger/boolean every frame as it would mean I need another if statement for every possible trigger. I don't want to make PlayScreen and Player's relation bidirectional either.

What would be the best or "correct" way to achieve this?

标签: javarelationship

解决方案


I would make use of the observer design pattern to solve this task. It should solve your problem of wanting to avoid a bidirectional coupling, because the PlayScreen (the observer in this case) would be notified of the changes to the Player (the observable in this case) as needed, but would otherwise have no reference to, or any other type of tight coupling to the Player.

If you're using Java, as the tags for this post indicate, here is a simple example in Java that should serve to demonstrate its use.


推荐阅读