在装饰器模式中实现委托

时间:2020-12-31 16:02:48

标签: javascript design-patterns decorator

如何将调用委派给包装对象 - 除了我更改的功能:

class Base {
    doSomething() {}
    doOtherSomething() {}
    doOtherSomething2() {}
}

class Decorator {
   constructor(wrapped) {
      this.wrapped = wrapped;
   }

    doSomething() { 
       console.log("doing more stuff");
       this.wrapped.doSomething()}
    }
}

如何委托其他函数在基类上自动调用?

1 个答案:

答案 0 :(得分:0)

假设您说的是一般意义上的包装(而不是几年来的各种装饰器提案),最简单的方法是根本不使用包装器。相反,要么:

  1. 使用子类(如果您想对一类对象执行此操作),或
  2. 将原始对象上的方法替换为您的替换对象,该方法调用您替换的原始对象(如果您想为单个对象执行此操作)。

#2 看起来像这样:

function wrapDoSomething(obj) {
    const original = obj.doSomething;
    obj.doSomething = function(...args) {
        // Do something here, then:
        return original.apply(this, args);
    };
    return obj; // Optional/nice to have
}

现场示例:

class Base {
   doSomething() {
       console.log("Original doSomething");
   }
   doOtherSomething() {
       console.log("Original doOtherSomething");
   }
   doOtherSomething2() {}
}

function wrapDoSomething(obj) {
    const original = obj.doSomething;
    obj.doSomething = function(...args) {
        console.log("wrapper doSomething - doing something before");
        const result = original.apply(this, args);
        console.log("wrapper doSomething - doing something after");
        return result;
    };
    return obj;
}

const b = wrapDoSomething(new Base());
b.doSomething();
b.doOtherSomething();