用ES6重寫《JavaScript Patterns》中的設計模式

前言

最近在回顧設計模式方式的知識,從新翻閱了《JavaScript模式》(我的感受也算是一本小有名氣的書了哈)一書,讀時總有感觸:在即將到來的ES6的大潮下,書中的許多模式的代碼可用ES6的語法更爲優雅簡潔的實現,而另外一些模式,則已經被ES6原生支持,如模塊模式(99頁)。因此本身動手用ES6從新實現了一遍裏面的設計模式,算是對其的鞏固,也算是與你們一塊兒來研究探討ES6語法的一些最佳實踐。php

目錄

(如下全部例子的原型均爲《JavaScript模式》一書裏「設計模式」章節中的示例)git

代碼repo地址,歡迎star,歡迎follow。github

實現

單例模式

主要改變爲使用了class的寫法,使對象原型的寫法更爲清晰,更整潔:設計模式

js'use strict';
let __instance = (function () {
  let instance;
  return (newInstance) => {
    if (newInstance) instance = newInstance;
    return instance;
  }
}());

class Universe {
  constructor() {
    if (__instance()) return __instance();
    //按本身需求實例化
    this.foo = 'bar';
    __instance(this);
  }
}

let u1 = new Universe();
let u2 = new Universe();

console.log(u1.foo); //'bar'
console.log(u1 === u2); //true

迭代器模式

ES6原生提供的Iterator接口就是爲這而生的啊,使用胖箭頭函數寫匿名函數(還順帶綁定了上下文,舒舒服服):數組

js'use strict';
let agg = {
  data: [1, 2, 3, 4, 5],
  [Symbol.iterator](){
    let index = 0;
    return {
      next: () => {
        if (index < this.data.length) return {value: this.data[index++], done: false};
        return {value: undefined, done: true};
      },
      hasNext: () => index < this.data.length,
      rewind: () => index = 0,
      current: () => {
        index -= 1;
        if (index < this.data.length) return {value: this.data[index++], done: false};
        return {value: undefined, done: true};
      }
    }
  }
};

let iter = agg[Symbol.iterator]();
console.log(iter.next()); // { value: 1, done: false }
console.log(iter.next()); // { value: 2, done: false }
console.log(iter.current());// { value: 2, done: false }
console.log(iter.hasNext());// true
console.log(iter.rewind()); // rewind!
console.log(iter.next()); // { value: 1, done: false }

// for...of
for (let ele of agg) {
  console.log(ele);
}

工廠模式

我的感受變化比較不大的一個:babel

js'use strict';
class CarMaker {
  constructor() {
    this.doors = 0;
  }

  drive() {
    console.log(`jaja, i have ${this.doors} doors`);
  }

  static factory(type) {
    return new CarMaker[type]();
  }
}

CarMaker.Compact = class Compact extends CarMaker {
  constructor() {
    super();
    this.doors = 4;
  }
};

CarMaker.factory('Compact').drive(); // 'jaja, i have 4 doors'

裝飾者模式

for...of循環,新時代的for (var i = 0 ; i < arr.length ; i++)? :函數

js'use strict';
class Sale {
  constructor(price) {
    [this.decoratorsList, this.price] = [[], price];
  }

  decorate(decorator) {
    if (!Sale[decorator]) throw new Error(`decorator not exist: ${decorator}`);
    this.decoratorsList.push(Sale[decorator]);
  }

  getPrice() {
    for (let decorator of this.decoratorsList) {
      this.price = decorator(this.price);
    }
    return this.price.toFixed(2);
  }

  static quebec(price) {
    return price + price * 7.5 / 100;
  }

  static fedtax(price) {
    return price + price * 5 / 100;
  }
}

let sale = new Sale(100);
sale.decorate('fedtax');
sale.decorate('quebec');
console.log(sale.getPrice()); //112.88

策略模式

對於傳統的鍵值對,使用Map來代替對象(數組)來組織,感受帶來得是更好的語義和更方便的遍歷:this

js'use strict';
let data = new Map([['first_name', 'Super'], ['last_name', 'Man'], ['age', 'unknown'], ['username', 'o_O']]);
let config = new Map([['first_name', 'isNonEmpty'], ['age', 'isNumber'], ['username', 'isAlphaNum']]);

class Checker {
  constructor(check, instructions) {
    [this.check, this.instructions] = [check, instructions];
  }
}

class Validator {
  constructor(config) {
    [this.config, this.messages] = [config, []];
  }

  validate(data) {
    for (let [k, v] of data.entries()) {
      let type = this.config.get(k);
      let checker = Validator[type];
      if (!type) continue;
      if (!checker) throw new Error(`No handler to validate type ${type}`);
      let result = checker.check(v);
      if (!result) this.messages.push(checker.instructions + ` **${v}**`);
    }
  }

  hasError() {
    return this.messages.length !== 0;
  }
}

Validator.isNumber = new Checker((val) => !isNaN(val), 'the value can only be a valid number');
Validator.isNonEmpty = new Checker((val) => val !== "", 'the value can not be empty');
Validator.isAlphaNum = new Checker((val) => !/^a-z0-9/i.test(val), 'the value can not have special symbols');

let validator = new Validator(config);
validator.validate(data);
console.log(validator.messages.join('\n')); //the value can only be a valid number **unknown**

外觀模式

這個簡直沒啥好變的。。。:設計

js'use strict';
let nextTick = (global.setImmediate == undefined) ? process.nextTick : global.setImmediate;

代理模式

利用extends關鍵字來得到父類中的方法引用以及和父類相同的類接口:代理

js'use strict';
class Real {
  doSomething() {
    console.log('do something...');
  }
}

class Proxy extends Real {
  constructor() {
    super();
  }

  doSomething() {
    setTimeout(super.doSomething, 1000 * 3);
  }
}

new Proxy().doSomething(); //after 3s ,do something...

訂閱/發佈模式

被Node原生的Events模塊所支持,一樣結合默認參數,for...of遍歷等特性,代碼的減小以及可讀性的增長都是可觀的:

js'use strict';
class Event {
  constructor() {
    this.subscribers = new Map([['any', []]]);
  }

  on(fn, type = 'any') {
    let subs = this.subscribers;
    if (!subs.get(type)) return subs.set(type, [fn]);
    subs.set(type, (subs.get(type).push(fn)));
  }

  emit(content, type = 'any') {
    for (let fn of this.subscribers.get(type)) {
      fn(content);
    }
  }
}

let event = new Event();

event.on((content) => console.log(`get published content: ${content}`), 'myEvent');
event.emit('jaja', 'myEvent'); //get published content: jaja

最後

以上全部代碼都可經過Babel跑通,90%以上的代碼可被當前版本的io.js(v2.0.2)跑通。

相關文章
相關標籤/搜索