Skip to content

Instantly share code, notes, and snippets.

@kyo-ago
Last active Jan 2, 2016
Embed
What would you like to do?
JavaScriptでDCI的なものを実装してみた例
// 銀行口座
var BankAccount = function (balance) { this.balance = balance; };
BankAccount.prototype.increase = function (money) { this.balance += money; };
BankAccount.prototype.decrease = function (money) { this.balance -= money; };
// ロール: 送信側
var Sender = function () {};
Sender.prototype.send = function (money, to) {
this.decrease(money);
to.onReceived(money, this);
};
// ロール:受信側
var Receiver = function () {};
Receiver.prototype.onReceived = function (money, to) {
this.increase(money);
};
// コンテキスト: 口座間送金
var TransferContext = function (from, to) {
Object.keys(TransferContext.prototype).filter(function (key) {
return 'function' == typeof this[key];
}.bind(this)).forEach(function (key) {
var func = this[key];
this[key] = function () {
var mixin = function (obj, ctx) {
var proto = obj.__proto__;
obj.__proto__ = ctx;
obj.__proto__.__proto__ = proto;
}
var cleanup = function (obj) {
obj.__proto__ = obj.__proto__.__proto__;
}
mixin(from, Sender.prototype);
mixin(to, Receiver.prototype);
func.apply(this, arguments);
cleanup(from);
cleanup(to);
};
}.bind(this));
this.from = from;
this.to = to;
};
TransferContext.prototype.transfer = function (money) {
this.from.send(money, this.to);
};
var from = new BankAccount(10);
var to = new BankAccount(10);
(new TransferContext(from, to)).transfer(10);
console.log(from.balance, to.balance); // 0 20
console.log(from.send, to.onReceived); // undefined undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment