Javascript設計模式-ES6寫法


前言

最近在回顧設計模式方式的知識,重新翻閱了《JavaScript模式》(個人感覺也算是一本小有名氣的書了哈)一書,讀時總有感觸:在即將到來的ES6的大潮下,書中的許多模式的代碼可用ES6的語法更為優雅簡潔的實現,而另一些模式,則已經被ES6原生支持,如模塊模式(99頁)。所以自己動手用ES6重新實現了一遍里面的設計模式,算是對其的鞏固,也算是與大家一起來研究探討ES6語法的一些最佳實踐。

目錄

(以下所有例子的原型均為《JavaScript模式》一書里“設計模式”章節中的示例)

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

實現

單例模式

主要改變為使用了class的寫法,使對象原型的寫法更為清晰,更整潔:

'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接口就是為這而生的啊,使用胖箭頭函數寫匿名函數(還順帶綁定了上下文,舒舒服服):

'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); }

工廠模式

個人感覺變化比較不大的一個:

'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++)? :

'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來代替對象(數組)來組織,感覺帶來得是更好的語義和更方便的遍歷:

'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**

外觀模式

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

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

代理模式

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

'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遍歷等特性,代碼的減少以及可讀性的增加都是可觀的:

'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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM