类的装饰器:ES6 中优雅的 mixin 式继承

zaxx7760 8年前
   <p>前几天翻译了一篇文章 <a href="http://www.open-open.com/lib/view/open1464826201796.html">六个漂亮的 ES6 技巧</a> ,作者介绍了通过 ES6 的新特性实现的 6 种编程技巧。其中最后一种技巧是:“ <a href="/misc/goto?guid=4959674116388870403" rel="nofollow,noindex"> Simple <strong>mixins</strong> via subclass factories </a> ”,我翻译成“通过子类工厂实现简单的合成器”。限于我自身英文水平,也许把 <strong>mixin</strong> 翻译成“合成器”并不是一个非常严谨的译法,加上作者对这个技巧介绍的篇幅有限,所举的例子比较简单,因此有些同学表示看到这里觉得不太懂。然而,这个技巧又是体现了很重要的设计模式——mixin和装饰器模式,因此我觉得有必要将它单独拎出来详细写一篇文章。</p>    <p><img src="https://simg.open-open.com/show/2be99eaed1fd76f16a987ccfded59129.jpg"></p>    <h2>ES5 的 mixin 模式</h2>    <p>熟悉 JavaScript 的同学应该对 mixin 模式并不陌生。我们说 JavaScript / ES5 的继承模型是基于单一原型链的继承模型,通常情况下,在 JavaScript 实践中完全用原型链来实现继承式的代码复用,是远远不能满足需求的。因此实战中,我们的代码抽象基本上都是采用混合的模式,既有原型继承,也有 mixin 组合。</p>    <p>那么什么是 mixin 呢? 最基本的 mixin 其实就是简单地 <strong>将一个对象的属性复制给另一个对象</strong> :</p>    <pre>  <code class="language-actionscript">function mixin(dest, src) {      for (var key in src) {          dest[key] = src[key]      }  }    var person = {name: "akira", age: 25};  var student = {grade: 1};  mixin(student, person);  </code></pre>    <p>上面的代码做的事情很简单,就是枚举出一个对象的所有属性,然后将这些属性添加到另一个对象上去。</p>    <p>有时候,我们需要将多个对象的属性 mixin 到一个对象上去:</p>    <pre>  <code class="language-actionscript">var dest = {...};  [src1, src2, src3].forEach(function(src){      mixin(dest, src);  });  </code></pre>    <p>每次都用 forEach 操作显然很繁琐,因此通常情况下, mixin 考虑支持操作多个对象:</p>    <pre>  <code class="language-actionscript">function mixin(...objs){      return objs.reduce((dest, src) => {          for (var key in src) {              dest[key] = src[key]          }          return dest;          });  }    var dest = mixin({...}, src1, src2, src3);  </code></pre>    <p>在许多框架中,都有 mixin 的类似实现, jQuery 的 extend、YUI 有好几个类似 mixin 的 API,lodash 中有 _.mixin 方法,npm 中的 <a href="/misc/goto?guid=4959674116481395485" rel="nofollow,noindex">mixin</a> 模块每个月有上千的下载。</p>    <p>jQuery 中的 extend</p>    <pre>  <code class="language-actionscript">var object1 = {    apple: 0,    banana: { weight: 52, price: 100 },    cherry: 97  };    var object2 = {    banana: { price: 200 },    durian: 100  };    // Merge object2 into object1  $.extend( object1, object2 );    // Assuming JSON.stringify - not available in IE<8  $( "#log" ).append( JSON.stringify( object1 ) );  </code></pre>    <p>ES5 中, <strong>mixin</strong> 为 object 提供功能“混合”能力,由于 JavaScript 的原型继承能力,通过 <strong>mixin</strong> 一个或多个对象到构造器的 prototype,也能够间接提供为“类”混合功能代码的能力。</p>    <p>下面是 <a href="/misc/goto?guid=4959674116570101707" rel="nofollow,noindex">例子</a> :</p>    <pre>  <code class="language-actionscript">function mixin(...objs){      return objs.reduce((dest, src) => {          for (var key in src) {              dest[key] = src[key]          }          return dest;          });  }    function createWithPrototype(Cls){      var P = function(){};      P.prototype = Cls.prototype;      return new P();  }    function Person(name, age, gender){      this.name = name;      this.age = age;      this.gender = gender;  }    function Employee(name, age, gender, level, salary){      Person.call(this, name, age, gender);      this.level = level;      this.salary = salary;  }    Employee.prototype = createWithPrototype(Person);    mixin(Employee.prototype, {      getSalary: function(){          return this.salary;      }  });    function Serializable(Cls, serializer){      mixin(Cls, serializer);      this.toString = function(){          return Cls.stringify(this);      }   }    mixin(Employee.prototype, new Serializable(Employee, {          parse: function(str){              var data = JSON.parse(str);              return new Employee(                  data.name,                  data.age,                  data.gender,                  data.level,                  data.salary              );          },          stringify: function(employee){              return JSON.stringify({                  name: employee.name,                  age: employee.age,                  gender: employee.gender,                  level: employee.level,                  salary: employee.salary              });          }      })  );  </code></pre>    <p>从一定程度上,mixin 弥补了 JavaScript 单一原型链的缺陷,可以实现类似于多重继承的效果。在上面的例子里,我们让 Employee “继承” Person,同时也“继承” Serializable。有趣的是我们通过 <strong>mixin</strong> Serializable 让 Employee 拥有了 stringify 和 parse 两个方法,同时改写了 Employee 实例的 toString 方法。</p>    <p>我们可以如下使用上面定义的类:</p>    <pre>  <code class="language-actionscript">var employee = new Employee("jane",25,"f",1,1000);  var employee2 = Employee.parse(employee+""); //通过序列化反序列化复制对象    console.log(employee2,       employee2 instanceof Employee,    //true       employee2 instanceof Person,    //true      employee == employee2);        //false  </code></pre>    <h2>ES6 中的 mixin 式继承</h2>    <p>在 ES6 中,我们可以采用全新的基于类继承 “mixin” 模式设计更优雅的“语义化”接口,这是因为 ES6 中的 extends 可以继承动态构造的类,这一点和其他的静态声明类的编程语言不同,在说明它的好处之前,我们先看一下 ES6 中如何更好地实现上面 ES5 代码里的 Serializable:</p>    <p><a href="/misc/goto?guid=4959674116653118861" rel="nofollow,noindex">用继承实现 Serializable</a></p>    <pre>  <code class="language-actionscript">class Serializable{    constructor(){      if(typeof this.constructor.stringify !== "function"){        throw new ReferenceError("Please define stringify method to the Class!");      }      if(typeof this.constructor.parse !== "function"){        throw new ReferenceError("Please define parse method to the Class!");      }    }    toString(){      return this.constructor.stringify(this);    }  }    class Person extends Serializable{    constructor(name, age, gender){      super();      Object.assign(this, {name, age, gender});    }  }    class Employee extends Person{    constructor(name, age, gender, level, salary){      super(name, age, gender);      this.level = level;      this.salary = salary;    }    static stringify(employee){      let {name, age, gender, level, salary} = employee;      return JSON.stringify({name, age, gender, level, salary});    }    static parse(str){      let data = JSON.parse(str);      return new Employee(data);    }  }    let employee = new Employee("jane",25,"f",1,1000);  let employee2 = Employee.parse(employee+""); //通过序列化反序列化复制对象    console.log(employee2,     employee2 instanceof Employee,  //true     employee2 instanceof Person,  //true    employee == employee2);   //false  </code></pre>    <p>上面的代码,我们用 ES6 的类继承实现了 Serializable,与 ES5 的实现相比,它非常简单,首先我们设计了一个 Serializable 类:</p>    <pre>  <code class="language-actionscript">class Serializable{    constructor(){      if(typeof this.constructor.stringify !== "function"){        throw new ReferenceError("Please define stringify method to the Class!");      }      if(typeof this.constructor.parse !== "function"){        throw new ReferenceError("Please define parse method to the Class!");      }    }    toString(){      return this.constructor.stringify(this);    }  }  </code></pre>    <p>它检查当前实例的类上是否有定义 stringify 和 parse 静态方法,如果有,使用静态方法重写 toString 方法,如果没有,则在实例化对象的时候抛出一个异常。</p>    <p>这么设计挺好的,但是它也有不足之处,首先注意到我们将 stringify 和 parse 定义到 Employee 上,这没有什么问题,但是如果我们实例化 Person,它将报错:</p>    <pre>  <code class="language-actionscript">let person = new Person("john", 22, "m");  //Uncaught ReferenceError: Please define stringify method to the Class!  </code></pre>    <p>这是因为我们没有在 Person 上定义 parse 和 stringify 方法。因为 Serializable 是一个基类,在只支持单继承的 ES6 中,如果我们不需要 Person 可序列化,而需要 Person 的子类 Employee 可序列化,靠这种继承链是做不到的。</p>    <p>另外,如何用 Serializable 让 JS 原生类的子类(比如 Set、Map)可序列化?</p>    <p>所以,我们需要考虑改变一下我们的设计模式:</p>    <p><a href="/misc/goto?guid=4959674116735811225" rel="nofollow,noindex">用 mixin 实现 Serilizable</a></p>    <pre>  <code class="language-actionscript">const Serializable = Sup => class extends Sup {    constructor(...args){      super(...args);      if(typeof this.constructor.stringify !== "function"){        throw new ReferenceError("Please define stringify method to the Class!");      }      if(typeof this.constructor.parse !== "function"){        throw new ReferenceError("Please define parse method to the Class!");      }    }    toString(){      return this.constructor.stringify(this);    }  }    class Person {    constructor(name, age, gender){      Object.assign(this, {name, age, gender});    }  }    class Employee extends Serializable(Person){    constructor(name, age, gender, level, salary){      super(name, age, gender);      this.level = level;      this.salary = salary;    }    static stringify(employee){      let {name, age, gender, level, salary} = employee;      return JSON.stringify({name, age, gender, level, salary});    }    static parse(str){      let data = JSON.parse(str);      return new Employee(data);    }  }    let employee = new Employee("jane",25,"f",1,1000);  let employee2 = Employee.parse(employee+""); //通过序列化反序列化复制对象    console.log(employee2,     employee2 instanceof Employee,  //true     employee2 instanceof Person,  //true    employee == employee2);   //false  </code></pre>    <p>在上面的代码里,我们改变了 Serializable,让它成为一个动态返回类型的函数,然后我们通过 class Employ extends Serializable(Person) 来继承可序列化,在这里我们没有可序列化 Person 本身,而将 Serializable 实际上从 <strong>语义上</strong> 变成了一种修饰,即 Employee 是一种 <strong>可序列化的 Person</strong> 。于是,我们要 new Person 就不会报错了:</p>    <pre>  <code class="language-actionscript">let person = new Person("john", 22, "m");   //Person {name: "john", age: 22, gender: "m"}  </code></pre>    <p>这么做了之后,我们还可以实现对原生类的继承,例如:</p>    <p><a href="/misc/goto?guid=4959674116818130356" rel="nofollow,noindex">继承原生的 Set 类</a></p>    <pre>  <code class="language-actionscript">const Serializable = Sup => class extends Sup {    constructor(...args){      super(...args);      if(typeof this.constructor.stringify !== "function"){        throw new ReferenceError("Please define stringify method to the Class!");      }      if(typeof this.constructor.parse !== "function"){        throw new ReferenceError("Please define parse method to the Class!");      }    }    toString(){      return this.constructor.stringify(this);    }  }    class MySet extends Serializable(Set){    static stringify(s){      return JSON.stringify([...s]);    }    static parse(data){      return new MySet(JSON.parse(data));    }  }    let s1 = new MySet([1,2,3,4]);  let s2 = MySet.parse(s1 + "");  console.log(s2,         //Set{1,2,3,4}              s1 == s2);  //false  </code></pre>    <p>通过 MySet 继承 Serializable(Set),我们得到了一个可序列化的 Set 类!同样我们还可以实现可序列化的 Map:</p>    <pre>  <code class="language-actionscript">class MyMap extends Serializable(Map){      ...  }  </code></pre>    <p>如果不用 mixin 模式而使用继承,我们就得分别定义不同的类来对应 Set 和 Map 的继承,而用了 mixin 模式,我们构造出了通用的 Serializable,它可以用来“修饰”任何对象。</p>    <p>我们还可以定义其他的“修饰符”,然后将它们组合使用,比如:</p>    <pre>  <code class="language-actionscript">const Serializable = Sup => class extends Sup {    constructor(...args){      super(...args);      if(typeof this.constructor.stringify !== "function"){        throw new ReferenceError("Please define stringify method to the Class!");      }      if(typeof this.constructor.parse !== "function"){        throw new ReferenceError("Please define parse method to the Class!");      }    }    toString(){      return this.constructor.stringify(this);    }  }    const Immutable = Sup => class extends Sup {    constructor(...args){      super(...args);      Object.freeze(this);    }  }    class MyArray extends Immutable(Serializable(Array)){    static stringify(arr){      return JSON.stringify({Immutable:arr});    }    static parse(data){      return new MyArray(...JSON.parse(data).Immutable);    }  }    let arr1 = new MyArray(1,2,3,4);  let arr2 = MyArray.parse(arr1 + "");  console.log(arr1, arr2,       arr1+"",     //{"Immutable":[1,2,3,4]}      arr1 == arr2);    arr1.push(5); //throw Error!  </code></pre>    <p>上面的例子里,我们定义了一个不可变数组,同时修改了它的序列化存储方式,而这一切,通过声明时 class MyArray extends Immutable(Serializable(Array)) 来实现。</p>    <h2>总结</h2>    <p>我们看到了 ES6 的 <strong>mixin</strong> 式继承的优雅和灵活,相信大家对它强大的功能和非常漂亮的装饰器语义有了比较深刻的印象了,在设计我们的程序模型的时候,我们可以开始使用它,因为我们有 Babel,以及 webpack 这样的工具能将它编译打包成 ES5,所以 ES6 早已不是什么虚无缥缈的东西。</p>    <p>记住 <strong>mixin</strong> 式继承的基本形式:</p>    <pre>  <code class="language-actionscript">const decorator = Sup => class extends Sup {      ...  }    class MyClass extends decorator(SuperClass) {    }  </code></pre>    <p>最后,除了使用类的 <strong>mixin</strong> 式继承之外,我们依然可以继续使用普通对象的 mixin,而且我们有了 ES6 的新方法 Obejct.assign,它是原生的实现 mixin 对象的方法。</p>    <p>有任何问题,欢迎讨论~</p>    <p> </p>    <p>来自: <a href="/misc/goto?guid=4959674116910615616" rel="nofollow">https://www.h5jun.com/post/mixin-in-es6.html</a></p>    <p> </p>