Java 中的组件模式:使用可重用组件简化复杂系统
约 3 分钟
又称
- 实体-组件-系统 (ECS)
- 组件-实体-系统 (CES)
- 基于组件的架构 (CBA)
组件设计模式的意图
组件设计模式将代码组织成可重用、可互换的组件,从而提高灵活性和模块化程度,并简化维护工作。这种模式在游戏开发中尤其有用,它使实体能够动态地配置各种行为。
组件模式的详细解释以及现实世界的例子
现实世界的例子
考虑一款具有图形组件和声音组件的视频游戏。将两者都包含在单个 Java 类中会由于代码过长以及不同团队在同一个类上工作时可能出现的冲突而造成维护困难。组件设计模式通过为图形和声音创建独立的组件类来解决这个问题,从而实现灵活的独立开发。这种模块化方法增强了可维护性和可扩展性。
简单来说
组件设计模式提供了一个单个属性,可供多个对象访问,而无需对象之间存在关系。
Java 中组件模式的编程示例
App
类通过创建两个继承了少量可修改的独立组件的不同对象来演示组件模式的使用。
public final class App {
public static void main(String[] args) {
final var player = GameObject.createPlayer();
final var npc = GameObject.createNpc();
LOGGER.info("Player Update:");
player.update(KeyEvent.KEY_LOCATION_LEFT);
LOGGER.info("NPC Update:");
npc.demoUpdate();
}
}
大部分程序位于 GameObject
类中,在这个类中,玩家和 NPC 对象创建方法被设置好。此外,该类还包含用于更新/更改对象组件信息的调用方法。
public class GameObject {
private final InputComponent inputComponent;
private final PhysicComponent physicComponent;
private final GraphicComponent graphicComponent;
public String name;
public int velocity = 0;
public int coordinate = 0;
public static GameObject createPlayer() {
return new GameObject(new PlayerInputComponent(),
new ObjectPhysicComponent(),
new ObjectGraphicComponent(),
"player");
}
public static GameObject createNpc() {
return new GameObject(
new DemoInputComponent(),
new ObjectPhysicComponent(),
new ObjectGraphicComponent(),
"npc");
}
public void demoUpdate() {
inputComponent.update(this);
physicComponent.update(this);
graphicComponent.update(this);
}
public void update(int e) {
inputComponent.update(this, e);
physicComponent.update(this);
graphicComponent.update(this);
}
public void updateVelocity(int acceleration) {
this.velocity += acceleration;
}
public void updateCoordinate() {
this.coordinate += this.velocity;
}
}
打开组件包后,将显示组件集合。这些组件为对象提供继承这些领域的接口。下面显示的 PlayerInputComponent
类根据用户的按键事件输入更新对象的 velocity 特性。
public class PlayerInputComponent implements InputComponent {
private static final int walkAcceleration = 1;
@Override
public void update(GameObject gameObject, int e) {
switch (e) {
case KeyEvent.KEY_LOCATION_LEFT -> {
gameObject.updateVelocity(-WALK_ACCELERATION);
LOGGER.info(gameObject.getName() + " has moved left.");
}
case KeyEvent.KEY_LOCATION_RIGHT -> {
gameObject.updateVelocity(WALK_ACCELERATION);
LOGGER.info(gameObject.getName() + " has moved right.");
}
default -> {
LOGGER.info(gameObject.getName() + "'s velocity is unchanged due to the invalid input");
gameObject.updateVelocity(0);
} // incorrect input
}
}
}
何时在 Java 中使用组件模式
- 用于游戏开发和模拟,其中游戏实体(例如角色、物品)可以具有动态的技能集或状态。
- 适用于需要高度模块化的系统,以及实体可能需要在运行时改变行为而无需继承层次结构的系统。
Java 中组件模式的现实世界应用
组件模式非常适合游戏开发和模拟,在这些场景中,角色和物品等实体具有动态的技能或状态。它适用于需要高度模块化和实体需要在运行时改变行为而无需依赖继承层次结构的场景,从而提高灵活性和可维护性。
组件模式的优缺点
优点
- 灵活性和可重用性:组件可以在不同的实体之间重用,从而更容易添加新功能或修改现有功能。
- 解耦:减少游戏实体状态和行为之间的依赖关系,从而更轻松地进行更改和维护。
- 动态组合:实体可以通过添加或删除组件来改变其运行时的行为,从而在游戏设计中提供极大的灵活性。
缺点
- 复杂性:可能会在系统架构中引入额外的复杂性,特别是在管理依赖关系和组件之间的通信时。
- 性能注意事项:根据实现方式,可能会由于间接性和动态行为而造成性能开销,尤其是在高性能游戏循环中至关重要。