A preliminary study of JavaScript design patterns

The singleton pattern

Internally define variables and determine by closure that new ones are generated if they do not exist

The strategy pattern

  • Consistent with the principle of single responsibility
  • Adding or subtracting policies without major changes to the original code
  • Multiple ways of dealing with the same problem are only different when specific behaviors are involved

See article :JavaScript eliminates if else and Switch with strategic patterns

const listString={
	add:0.del:1.update:2
}

const strFunc={
	add:function(){
		return listString['add'];
	},
	del:function(){
		return listString['del'];
	},	
	update:function(){
		return listString['update']; }}function getData(name){
	returnstrFunc[name]? strFunc[name]():0;
}

console.log(getData('add'));
Copy the code

The proxy pattern

Control of method content before accessing the body

For example: click loginData validation, the login interface will be accessed only after passing

const login(name){
	console.log(name+'Logged in');
}

const proxyCheckLogin(name){
	if(! name)return
	login(name);
}
Copy the code

Publish and subscribe

One party publishes events and the other subscribes to receive events

For example: such as the vuex vue, the React of mobx | story is the form of faults:

  • Resident memory adds performance overhead
  • As projects get larger, it becomes harder to keep track of subscriptions

The mediator pattern

All methods are implemented through the mediator method, which notifies the mediator when the content changes

An example is to split the parts of a method that are shared into separate functions

function add(name){
	let temp='1';
	consoleFunc(temp,name);
}
function update(name){
	let temp='2';
	consoleFunc(temp,name);
}
function consoleFunc(temp,name){
	console.log(name+'output :'+temp);
}
add('zhangsan');
update('lisi');
Copy the code

Decorator pattern

To the existing object or method content supplement and extend, give more ability

For example, Xiao Ming could only eat with chopsticks, but after passing the decoration, he learned to use a knife and fork

function Person() {}

Person.prototype.skill = function() {
    console.log('mathematics');
};

// Can also play music
function MusicDecorator(person) {
    this.person = person;
}

MusicDecorator.prototype.skill = function() {
    this.person.skill();
    console.log('music');
};
var person = new Person();

// Decorate it
var person1 = new MusicDecorator(person);

person.skill(); / / math
person1.skill(); // Math music
Copy the code

The state pattern

Encapsulating the state, the state is already defined and the user does not need to know

For example: turning on the light, turning off the light, just changing the state through state mode

Adapter mode

Adapt the parts that do not fit between methods

For example: Foreach parses array data, but passes in an object, so it’s time to judge and adapt

// Render data in array format
function renderData(data) {
    data.forEach(function(item) {
        console.log(item);
    });
}

// ADAPTS non-array conversions
function arrayAdapter(data) {
    if (typeofdata ! = ='object') {
        return [];
    }

    if (Object.prototype.toString.call(data) === '[object Array]') {
        return data;
    }

    var temp = [];

    for (var item in data) {
        if(data.hasOwnProperty(item)) { temp.push(data[item]); }}return temp;
}

var data = {
    0: 'A'.1: 'B'.2: 'C'
};

renderData(arrayAdapter(data)); // A B C
Copy the code

The appearance model

Define a function to hold the other functions and execute them all together

For example: is to beautify…………..

// Three handlers
function add() {
    console.log('add');
}

function update() {
    console.log('update');
}

// Appearance function, unify some processing, easy to call
function execute() {
    add();
    update();
}

// Call init to start execution
function init() {
    // Call the higher-level function directly, or you can skip it and call the related function directly
    execute();
}

init(); // add update
Copy the code

Iterator pattern

The iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing the internal representation of the object

No application scenario exists

function add(){

	console.log('add');
	return false;
}
function update(){
	console.log('update');
	return false;
}
function iteratorFunc() {
    for (var i = 0; i < arguments.length; ++i) {
        var ret = arguments[i]();
        if(ret ! = =false) {
            returnret; }}}var temp=iteratorFunc(add,update);
Copy the code

Chain of Responsibility model

Call one by one until a function method handles the request for example: similar to if/else

Template method pattern

Encapsulates subclass methods and instructs subclasses which methods to execute in which order

The flyweight pattern

Reduce the number of shared objects

Portfolio model

Is to build larger objects out of small children, which themselves may be made up of even smaller grandchildren

Command mode

A command is an instruction to do something specific