首先,事件编程或继承与 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/看到