4

我最近看到了 Trygve Reenskaug 关于 DCI 的以下演示: https ://vimeo.com/43536416 这让我大吃一惊。嗯,在代码中看到软件不同组件之间的交互是一个很有吸引力的想法。

我试图在 javascript 中找到 DCI 的示例,但没有成功。然后我开始怀疑。DCI模式不是与事件编程模式相反吗?

事件编程在 javascript 中很流行,我猜是因为它允许解耦,并且因为经典继承概念不是 js 原生的。我想我了解事件编程的好处,但我也注意到当需要跟踪事件消息时,调试可能会非常困难。

说这两个概念是对立的是否正确?还是我弄错了?是否有一些我错过的 js 中 DCI 的示例实现?为了挖掘这个概念,我应该看什么?

4

1 回答 1

5

首先,事件编程或继承与 DCI 正交。您可以在没有继承和事件编程(或没有)的情况下进行 DCI。

JavaScript 在某些方面是执行 DCI 的最佳语言之一。大多数语言在严格遵循 DCI 方面存在一些问题。在 JavaScript 中,如果有终结器,则可以解决问题,但缺少终结器意味着您将不得不“处理”您自己,这意味着一些 noilerplate 代码。

我用 JavaScript 编写了一个示例,我将把它放到http://fullOO.info上,在那里您可以找到 Trygve、Jim 和我与其他人一起创建的示例。

fullOO.info 也是您可以去哪里更熟悉 DCI 的答案,或者您可以加入 object-composition 一个 Google 小组讨论有关 DCI 的问题。

我用 JS 编写的示例是规范的 DCI 示例汇款,有趣的部分(除了样板/库代码之外的所有内容)如下所示:

var moneyTransferContext = function(sourcePlayer, destinationPlayer, amount) {
    var source = {
            withdraw: function() {
                var text = "Withdraw: " + amount;
                this.log.push(text);
                this.balance -= amount;
                console.log("Balance: " + this.balance);
            }
        },
        destination = {
            deposit: function() {
                var text = "Deposit: " + amount;
                this.log.push(text);
                this.balance += amount;
                console.log("Balance: " + this.balance);
            }
        };
    source = assign(source).to(sourcePlayer);
    destination = assign(destination).to(destinationPlayer);
    return {
        transfer: function() {
            source.withdraw();
            destination.deposit();
            return this;
        }
    };
},
sourceAccount = {
  log: [],
  balance: 100
},
destinationAccount = {
  log: [],
  balance: 0
};

moneyTransfer(sourceAccount, destinationAccount, 25).transfer().unbind();

其余的可以在http://jsfiddle.net/K543c/17/看到

于 2012-10-09T10:39:06.280 回答