Introduction to JavaScript Design Patterns and Practice in Frameworks

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

In the following, the author will briefly introduce the use of design patterns in these libraries, grammars and frameworks in combination with subscribe in redux, class in ES6, $dispatch in vue, and on/off in jquery.

 

Problems solved by design patterns

Design patterns are not very mysterious knowledge. Many students have inadvertently used a lot of design patterns when writing js code.

 

The author thinks that abstracting and discussing design patterns is the same as abstracting bubbling and sorting in algorithms, in order to describe a commonly used JS pattern.

By studying such patterns, let the patterns guide our code structure and JS algorithms.

 

An overview of some commonly used design patterns

1, observer [observer mode]

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

A simple observer pattern code practice

class StateTracker{
	constructor(){
		this.observers = [];
		this.internalState= 10;
	}
	// Change the internal state, the list of observers that trigger the state
	change(val){
		this.internalState= val;
		this.observers.forEach(observer=>observer(val));
	}// Register an observer
	registerObserver(ObserverFn){
		this.obserers.push(ObserverFn)
	}
}

2. publish/subscribe [subscription publishing mode]

Store the topic/callback form of the 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-publishing mode code practice

class PubSubHandler{
	constructor(){
		this.eventPool = {};
	}
	//remove
	off(topicName){
		delete this.observers[topicName]
	}
	//release
	trigger(topicName,...args){
		this.eventPool[topicName] && 
		this.eventPool[topicName].forEach(callback=>callback(...args));
	}
	//subscription
	on(topicName,callback){
		let topic = this.eventPool[topicName] ;
		if(!topic){
			this.eventPool[topicName] =[]
		}
		this.eventPool[topicName].push(callback)
	}
}

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;
	}// Singleton mode method entry
	return {
		getInstance:()=>{
			if(!instance){
				instance = createInstance();
			}
			return instance;
		}
	}
}
var test = singleton();
test.getInstance() == test.getInstance() //true

4, decorator decorator pattern

This pattern is to decorate more behavior on the original object, and keep the variable name 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){
	decortorFn(sourceObj);
	return sourceObj
}
var d = {a:1};
// d becomes {a:1,b:1}
d = decorator(d,(d)=>{d.b=1});

5, mixin mixing mode

This mode is somewhat similar to the decorator, except that it functions more vertically.

 

It is the behavior of adding and overwriting objects on top of the original objects.

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

The mixin mode cannot be generalized. There may be different mixin strategies according to different data types, such as vue.mixin

A simple mixed-mode code practice

class StateTracker{
	constructor(){
		this.raw = {
			a:1,
			b:2
		}
	}// Mixed mode method entry
	mixin(obj){
		Object.assign(this.raw,obj)
	}
}

The author briefly introduces so many design patterns.

 

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

 

Example code for using observer mode in redux

var store = createStore(reducer,initialState);
//Register the redux store and store it in the nextListeners array
var test = store.subscribe(()=>{console.log('I'm registered!')});
// unregister listener
test.unsubscribe();

Resource search website Daquan https://www.renrenfan.com.cn Guangzhou VI Design Companyhttps://www.houdianzi.com

Example code for use of publish/subscribe in jquery

$(document).on('hello',()=>{console.log('hello')})
$(document).trigger('hello');
$(document).off('hello')

 

Practice of decorator pattern in react-redux

//decorator
@connect(state=>state)
class Container extends Component{
	render(){
		return JSON.stringify(this.props)   
	}
}

Tags: Javascript

Posted by Coco on Mon, 02 May 2022 14:20:19 +0300