java - 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?
解决方案
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.
推荐阅读
- powershell - 提取由特定字符分隔的两个字符串
- pjsip - 邀请后在 SIP OK 中缺少 SDP 信息
- semantic-web - DL Expressivity 在 Protégé Ontology Metrics 视图中不可用
- java - 在没有编辑文本的情况下捕获软键盘上的完成操作?
- visual-studio-code - vscode 和 plantuml 2.11.1 无法包含环境变量指定的文件
- python - PermissionError 与 RandomizedSearchCV
- gradle - IDEA 以及如何禁用 gradle 包装器生成?
- recursion - 通过 html 标签的值进行抓取链接提取器
- github - 如何使用 git 从旧提交中提取代码?
- laravel-5.8 - 为 foreach() laravel5.8 提供的参数无效