I noticed that when using something like XNA/C# (game engine) a while ago that you simply added components to an object and that gave it extra functionality. For example:
Class Spaceship has components, Collidable, Gravity, Controls and more...
Typically these components implement IUpdatable/IDrawable Interfaces or DrawableGameComponent or something else: https://gamedev.stackexchange.com/questions/20918/what-happens-when-i-implement-iupdateable-or-idrawable-in-xna
When it comes time to update/draw or some other "event" all components get called that have those events on them, which makes me think of observer pattern. Yet these functions seem like they are "decorating" the main class.
Is this a known pattern? What is it called? Is this a good pattern to use beyond game dev? The reason I tagged JavaScript is because I was thinking about doing something like this in JS, and I was wondering if anyone has seen someone do something similar.
It may look something like this:
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));
}
Events might then get triggered and all of cars components would be updated.