Javascriptでデザインパターン (その7: Chain of Responsibility) - まめージェント読んだ。委譲先での処理に非同期処理を含まないパターンなら、単純にユーザーインターフェース(client)に登録した処理器を順番に実行していったほうがシンプルだと思うし、
var client = new Client(
new TyepCheck
, new MinLengthCheck(min_length)
, new MaxLengthCheck(max_length)
, new MainHandler
)
client.request(foo)
のような書き方の方が(自分には)わかりやすいかなと。
client.js
function Client () {
this.validators = [].slice.apply(arguments).filter(flt)
}
function flt (validator) {
return 'function' === typeof (validator || {}).request
}
Client.prototype.request = function (input) {
for (var i = 0; i < this.validators.length; i++) {
this.validators[i].request(input)
}
}
type-check.js
function TypeCheck () {}
TypeCheck.prototype.request = function (input) {
if ('string' !== typeof input)
throw new TypeError('"input" must be "string"')
return !0
}
min-length-check.js
function MinLengthCheck (min_length) {
this.min_length = min_length
}
MinLengthCheck.prototype.request = function (input) {
if (this.min_length < input)
throw new Error('too short')
return !0
}
max-length-check.js
function MaxLengthCheck (max_length) {
this.max_length = max_length
}
MinLengthCheck.prototype.request = function (input) {
if (this.max_length > input)
throw new Error('too long')
return !0
}
main-handler.js
function MainHandler () {}
MainHandler.prototype.request = function (input) {
console.log('validate ok - "%s"', input)
return !0
}
実際に使ってみる
main.js
var client = new Client(
new TypeCheck
, new MinLengthCheck(4)
, new MaxLengthCheck(6)
, new MainHandler
)
test()
test('lg')
test('looooog!!')
test('log')
function test (input) {
try {
client.request(input)
} catch (err) {
console.error(err)
}
}