Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9060

【PHPとNodejs デコレータパターンの実装を比較してみる】

$
0
0

同じようなことをしたい場合この2つの言語でどんな差があるのか気になったので比較してみた。

Node.jsはシンプルにかけるなーと感じました。

PHP

以下のクラス図に沿って実装してみる

36593375-1D87-471B-8BA7-DD339B465525_4_5005_c.jpeg

他のほとんどの言語でもおなじような実装になるとおもう。

Component interface

interfaceComponent{publicfunctionoperation();}

ConcreteComponent class

classconcreteComponentimplementsComponent{publicfunctionoperation(){}}

Decorator class

classDecoratorimplementsComponent{private$component;publicfunction__construct(Component$component){$this->component=$component;}publicfunctionoperation(){}}

ConcreteDecorator class

classconcreteDecoratorextendsDecorator{publicfunction__construct(Component$component){parent::__construct($component);}// デコレートする関数をここに書くpublicfunctionaddedBehavior(){parent::operation();//ここの返り値をデコレートしたりする}}

Node.js

できるだけ上の画像と同じようなイメージで実装してみる。
もとになるcomponentオブジェクトを拡張(デコレート)するときを考える。
Proxyパターンにおけるオブジェクトの拡張も同じように実装できるらしい
注意点は、もとのオブジェクトを上書きしているというところ。

Decorator

exports.decorate=(component)=>{// デコレートする関数component.addedBehavior=()=>{}returncomponent}

component(拡張したいオブジェクト)

component={operation:()=>{}}module.exports=component

concreteDecorator

constcomponent=require('./component')constdecorator=require('./decorator')decorator.decorate(component)console.log(component)//componentにaddedBehavior()が拡張されている

Viewing all articles
Browse latest Browse all 9060

Latest Images

Trending Articles