Introduction to JS design pattern and practice in the framework

Introduction to JS design pattern and practice in the framework

This article is an original article by Lecturer Slashhuang from Hungry Man Valley .

In the process of writing JS code, using certain design patterns can make our code more elegant and flexible.

Next, I will combine subscribe of redux, class of ES6, $dispatch in vue, and on/off in jquery to give you a brief introduction to the use of design patterns in these libraries, syntaxs and frameworks.

Problems solved by design patterns

Design patterns are not very mysterious. Many students have inadvertently used many design patterns when writing JS code.

The author believes that the design pattern is abstracted out and discussed separately, just like the bubble and sorting abstracted out of the algorithm, it is to describe a commonly used JS pattern.

By studying this kind of pattern, let the pattern guide our code structure and JS algorithm.

Overview of some commonly used design patterns

1. Observer [observer mode]

Actively trigger the callback behavior of the observer queue and hashMap according to the change of the state

A simple observer pattern code practice

    class StateTracker{
            this.observers = [];
            this.internalState= 10;
            this.internalState= val;

2. publish/subscribe [Subscription publishing mode]

Store the topic/callback form of hashMap in the shared access space of the code module.

Add on/off/trigger and other interfaces to implement actions such as mounting, removing, and triggering.

A simple subscription release mode code practice

    class PubSubHandler{
            this.eventPool = {};
            delete this.observers[topicName]
            this.eventPool[topicName] && 
            let topic = this.eventPool[topicName] ;
                this.eventPool[topicName] =[]

3. Singleton [singleton mode]

There is only one instance of the constructor. Generally, the internal instance is stored through the closure, and the internal instance is accessed through the interface.

A simple singleton pattern code practice

    var singleton = ()=>{
        var instance;
        var createInstance = ()=>{
            this.a = 1;
            this.b = 2;
        return {
                    instance = createInstance();
                return instance;
    var test = singleton();
    test.getInstance() == test.getInstance()//true

4. Decorator mode

This mode is to decorate more behaviors on the original objects and keep the variable names unchanged.

Those who have used ES7's @decorator or python and other languages should be familiar with decorators.

A simple decorator pattern code practice

    function decorator(sourceObj,decortorFn){
        return sourceObj
    var d = {a:1};
   //d {a:1,b:1}
    d = decorator(d,(d)=>{d.b=1});

5. Mixin mixed mode

This mode is similar to decorator, but its function is more vertical.

It is the act of adding or overwriting objects on the original objects.

Compared with methods such as extends and Object.assign, the mixin mode is more expressive.

The mixin model cannot be generalized. There may be different mixin strategies based on different data types, such as vue.mixin.

A simple mixed mode code practice

    class StateTracker{
            this.raw = {

I will introduce so many design patterns for now.

The following describes the application of these design patterns for commonly used frameworks, syntaxs, libraries, etc.

Sample code for the use of observer mode in redux

    var store = createStore(reducer,initialState);
   //redux store  nextListeners 
    var test = store.subscribe(()=>{console.log(' ')});

Use sample code of publish/subscribe in jquery


The practice of decorator pattern in react-redux

    class Container extends Component{
            return JSON.stringify(this.props)   


Regarding the practice of design patterns in front-end frameworks or libraries, what I have written here is relatively brief. Students who may not have written relevant code are not particularly easy to understand. Students who have related questions can directly ask questions at the end of the article.

I hope this article can help you learn and understand the concept of design patterns.

This article was first published on the author's github blog

github design pattern tutorial code address

Add WeChat ID: xiedaimala03, password: write code

One question a day, weekly resource recommendation, wonderful blog recommendation, work, written test, interview experience exchange answers, free live class, group friends light sharing..., countless benefits are given for free