3

我注意到不久前使用 XNA/C#(游戏引擎)之类的东西时,您只需将组件添加到对象并赋予它额外的功能。例如:

类 Spaceship有组件,CollidableGravityControls等等......

通常这些组件实现 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));
}

然后可能会触发事件并更新所有汽车组件。

4

2 回答 2

2

我认为您的意思是 mixins (Javascript) 或 Traits (PHP)

Mixins 基本上只是 _.extend'ing(或 $.extend'ing)您当前的对象与另一个对象(已经具有一些属性/功能)。您可以在http://www.joezimjs.com/javascript/javascript-mixins-functional-inheritance/上阅读更多内容

PHP (5.4) 的特性更强大,你可以做很多很酷的事情。这是来自 stackoverflow 的一个很好的例子:PHP 中的特征——任何现实世界的例子/最佳实践?

于 2012-10-16T22:54:48.663 回答
1

复合图案?

Component为常见的行为(update方法)定义一个接口( )

让所有组件实现Component(可碰撞、重力、控制等)

让父类SpaceShip维护一个Components列表

让父类也SpaceShip实现 Component

从客户的角度来看SpaceShip,它是一个提供update方法的对象。

在内部,在它的update方法中,SpaceShip调用update所有Component

于 2012-10-18T06:50:14.863 回答