我注意到不久前使用 XNA/C#(游戏引擎)之类的东西时,您只需将组件添加到对象并赋予它额外的功能。例如:
类 Spaceship有组件,Collidable,Gravity,Controls等等......
通常这些组件实现 IUpdatable/IDrawable 接口或 DrawableGameComponent 或其他东西:https ://gamedev.stackexchange.com/questions/20918/what-happens-when-i-implement-iupdateable-or-idrawable-in-xna
当需要更新/绘制或其他一些“事件”时,所有组件都会被调用,这些组件上都有这些事件,这让我想到了观察者模式。然而,这些功能似乎是在“装饰”主类。
这是一个已知的模式吗?这叫什么?这是一个在游戏开发之外使用的好模式吗?我标记 JavaScript 的原因是因为我正在考虑在 JS 中做类似的事情,我想知道是否有人见过有人做类似的事情。
它可能看起来像这样:
function Watcher() {
this.components = [];
this.update() = function() {
for (component in this.components) {
if (typeof component.update === "function") {
component.update();
}
}
};
}
function Component() {
this.update = function() {
};
}
function Wiggle(obj) {
_.extend(this, Component.prototype);
this.obj = obj;
this.wiggled = false;
this.update = function() {
if (this.wiggled) {
this.obj.x -= 1;
} else {
this.obj.x += 1;
}
wiggled = !wiggled;
};
}
function Car() {
this.x = 0;
_.extend(this, Watcher.prototype);
this.components.push(new Wiggle(this));
}
然后可能会触发事件并更新所有汽车组件。