
6.4
デコレータ
169
既存のメソッドの呼び出しをインターセプトし変更してしまうこともできます。
6.4.1
デコレータの実装
プロキシとデコレータは、概念としては別々の意図をもった異なるパターンなのですが、実際には実
装の方法は共通です。
6.4.1.1
合成
合成の場合、デコレートされるコンポーネントは、通常それを継承して生成されるオブジェクトで
ラップされる形になります。デコレータは新しいメソッドを定義するだけで、既存のメソッドは元のコ
ンポーネントに委譲されます(
12_decorator_a
)。
function decorate(component) {
const proto = Object.getPrototypeOf(component);
function Decorator(component) {
this.component = component;
}
Decorat
or.prototype = Object.create(proto);
//
新しいメソッド
Decorator.prototype.greetings = function() {
return 'Hi!';
};
//
委譲されるメソッド
Decorator.prototype.hello = function() {
return this.component.hello.apply(this.component, arguments);
};
return new Decorator(component); ...