比較PHP和Node.js实现装饰器模式
因为我好奇如果要做类似的事情,这两种语言有什么区别,所以我进行了比较。
我觉得Node.js可以简化很多东西。
PHP (现在又被称为PHP: Hypertext Preprocessor) 是一种开源的通用脚本语言,适用于Web开发。
按照以下的类图尝试进行实现。

我认为在大多数其他语言中,实现方式也会相似。
<<界面>> 组件
interface Component {
public function operation();
}
具体组件
class concreteComponent implements Component{
public function operation(){
}
}
装饰者模式
class Decorator implements Component{
private $component;
public function __construct(Component $component){
$this->component = $component;
}
public function operation(){
}
}
具体装饰者 zhě)
class concreteDecorator extends Decorator{
public function __construct(Component $component){
parent::__construct($component);
}
// デコレートする関数をここに書く
public function addedBehavior(){
parent::operation(); //ここの返り値をデコレートしたりする
}
}
Node.js(简称Node)是一个基于Chrome V8 JavaScript引擎的服务器端运行环境。
尽量以与上方图片相似的形象进行实施。
考虑扩展(装饰)基础组件对象的情况。
据说在代理模式中,也可以以相同的方式实现对象的扩展。
需要注意的是,正在覆盖原始对象。
对象扩展
装饰者 zhě)
exports.decorate = (component) => {
// デコレートする関数
component.addedBehavior = () => {
}
return component
}
组件(需要扩展的对象)
function component(){}
component.prototype.operation = () => {return 'hello'}
module.exports = new component()
具体装饰器
const component = require('./component')
const decorator = require('./decorator')
decorator.decorate(component)
console.log(component) //componentにaddedBehavior()が拡張されている
对象合成
如果想要在保留现有对象的基础上进行扩展,可以采取合成的方法。在内部持有现有对象,并在调用现有对象的方法时进行委托处理。
exports.decorate = (component) => {
const proto = Object.getPrototypeOf(component)
const Decorator = function(component){
this.component = component
}
Decorator.prototype = Object.create(proto)
Decorator.prototype = {
// デコレートする関数
addedBehavior: () =>{
},
operation: () => {
return this.component.operation.apply(this.component, arguments)
}
}
return new Decorator(component)
}