JS設計模式入門和框架中的實踐
在編寫JS代碼的過程中,運用一定的設計模式可以讓我們的代碼更加優雅、靈活。
下面筆者就結合諸如redux的subscribe、ES6的class、vue里面的$dispatch、jquery里面的on/off來給大家簡單介紹下設計模式在這些庫、語法和框架中的使用。
設計模式解決的問題設計模式并不是很玄乎的知識,很多同學在編寫JS代碼的時候已經在不經意間用了不少設計模式了。
筆者認為把設計模式單獨抽象出來探討,就和算法中抽象出來冒泡、排序一樣,是為了描述一種常用的JS pattern。
通過研習這類pattern,讓模式來指導我們的代碼結構及JS算法。
一些常用的設計模式概述1、observer [觀察者模式]
根據狀態的變化主動觸發觀察者隊列、hashMap的回調行為
一個簡單的觀察者模式代碼實踐
class StateTracker{constructor(){ this.observers = []; this.internalState= 10;}// 改變內部狀態,觸發狀態的觀察者列表change(val){ this.internalState= val; this.observers.forEach(observer=>observer(val));}// 注冊觀察者registerObserver(ObserverFn){ this.obserers.push(ObserverFn)} }
2、publish/subscribe [訂閱發布模式]
在代碼模塊的共享訪問空間存儲hashMap的topic/callback形式。
添加on/off/trigger等接口實現掛載、移除、觸發等動作。
一個簡單的訂閱發布模式代碼實踐
class PubSubHandler{constructor(){ this.eventPool = {};}//移除off(topicName){ delete this.observers[topicName]}//發布trigger(topicName,...args){ this.eventPool[topicName] && this.eventPool[topicName].forEach(callback=>callback(...args));}//訂閱on(topicName,callback){ let topic = this.eventPool[topicName] ; if(!topic){this.eventPool[topicName] =[] } this.eventPool[topicName].push(callback)} }
3、singleton[單例模式]
一個簡單的單例模式代碼實踐
var singleton = ()=>{var instance;var createInstance = ()=>{ this.a = 1; this.b = 2;}// 單例模式方法入口return { getInstance:()=>{if(!instance){ instance = createInstance();}return instance; }} } var test = singleton(); test.getInstance() == test.getInstance() //true
4、decorator裝飾者模式
這個模式就是在原有的對象上面裝飾更多行為,并且保持變量名不變。
用過ES7的@decorator或者python等語言的,應該對decorator不陌生的。
一個簡單的裝飾者模式代碼實踐
function decorator(sourceObj,decortorFn){decortorFn(sourceObj);return sourceObj } var d = {a:1}; // d變為了{a:1,b:1} d = decorator(d,(d)=>{d.b=1});
5、mixin混合模式
這個模式和decorator有點類似,只是它的功能更加垂直。
就是在原有的對象上面增加、覆蓋對象的行為。
相比于extends、Object.assign等方法,mixin模式更富有表現力。
mixin模式不能一概而論,可能依據不同的數據類型有不同的mixin策略,比如vue.mixin
一個簡單的混合模式代碼實踐
class StateTracker{constructor(){ this.raw = {a:1,b:2 }}// 混合模式方法入口mixin(obj){ Object.assign(this.raw,obj)} }
下面就針對常用的框架、語法、庫等來說明這些設計模式的應用。
observer模式在redux中的使用示例代碼var store = createStore(reducer,initialState); //注冊redux store,存儲在 nextListeners數組 var test = store.subscribe(()=>{console.log(’我注冊了!’)}); // 取消注冊監聽 test.unsubscribe(); publish/subscribe在jquery中的使用示例代碼
$(document).on(’hello’,()=>{console.log(’hello’)}) $(document).trigger(’hello’); $(document).off(’hello’) decorator模式在react-redux中的實踐
//裝飾器 @connect(state=>state) class Container extends Component{render(){ return JSON.stringify(this.props) } } 總結
關于設計模式在前端框架或庫的實踐,我這邊寫的是比較簡略的, 可能沒有寫過相關代碼的同學不是特別好理解,有相關疑問的同學可以在文末直接提問。
希望本文能夠對大家學習和了解設計模式的概念有所了解
本文首發于筆者的 github blog
github設計模式教程代碼地址
來自:https://segmentfault.com/a/1190000012814591
相關文章: