美文网首页
装饰者模式 decorate

装饰者模式 decorate

作者: 15d843cd48a8 | 来源:发表于2017-10-19 02:12 被阅读37次

    装饰者模式:在不改变原对象的基础上,通过对其进行包装(添加属性或方法)使原有对象可以满足更复杂需求。

    在面向对象语言中,给对象添加功能一般使用继承的方式,但是继承的方式并不灵活,导致超类和子类之间存在强耦合性,当超类改变时,子类也会改变。


    装饰者也是包装器,它将一个对象嵌入另一个对象之中,相当于这个对象被另一个对象包装起来。


    我们装饰 a 函数:

    var a = function() {
      alert(1)
    }
    
    // 改成
    var a = function() {
      alert(1)
      alert(2)
    }
    

    违反了开放-封闭原则

    var a  = function() {
      alert(1)
    }
    
    var _a = a
    
    a = function() {
      _a()
      alert(2)
    }
    
    a()
    

    但是这样,我们要维护 _a 变量,很不优雅。


    AOP 装饰函数

    Function.prototype.before = function(beforefn) {
      var self = this
      return function() {
        beforefn.apply(this, arguments)  // 执行新函数,保证 this 不被劫持
        return self.apply(this, arguments) // 执行原函数并返回原函数执行结果
      }
    }
    
    Function.prototype.after = function(afterfn) {
      var self = this
      return function() {
        var ret = self.apply(this, arguments)
        afterfn.apply(this, arguments)
        return ret
      }
    }
    

    再看上面的例子:

    var a  = function() {
      alert(1)
    }
    
    a = a.after(function() {
      alert(2)
    }).after(function() {
      alert(3)
    })
    
    a()
    

    类和方法的装饰器: @

    @decorator
    class A {}
    
    // 等同于
    
    class A {}
    A = decorator(A) || A;
    

    相关文章

      网友评论

          本文标题:装饰者模式 decorate

          本文链接:https://www.haomeiwen.com/subject/vtweuxtx.html