JavaScript Decoratorパターン
Decoratorパターンの良いところは、
主体となるオブジェクトと、処理を委譲しているオブジェクトの間に、スッと割り込ませることが出来ること。
そして、その処理を委譲しているオブジェクトには、傷をつけなくて済む。
Decoratorでラッピングするか否か、動的に決めることも出来る。
処理を付け足したり、付け足さなかったり…そんな時に使えるかも。使いたい。けど使いにくい。
function Component() { this.showNumber = function () { console.log(2) } } function Decorator(component) { this.component = component this.showNumber = function () { console.log(1) this.component.showNumber() console.log(3) } } var decorator = new Decorator(new Component()) decorator.showNumber()
1
2
3
Componentの処理のど真ん中に、Decoratorからの処理を埋め込みたい…そんな時もあるかもしれない。
function Component() { this.showNumber = function () { console.log(2) this.decorator.showInnerNumber() console.log(4) } } function Decorator(component) { this.component = component this.component.decorator = this this.showNumber = function () { console.log(1) this.component.showNumber() console.log(5) } this.showInnerNumber = function () { console.log(3) } } var decorator = new Decorator(new Component()) decorator.showNumber()
1
2
3
4
5
DecoratorはComponentを持ち、ComponentもDecoratorを持つ。お互いに委譲し合っている。
イマイチかもしれない。急遽、応急処置が必要な時に使おう。