Preliminary study on design mode
Singleton mode
Variables are defined internally and judged by closures. If they do not exist, new variables are generated
Strategy mode
- Consistent with the principle of single responsibility
- Add or reduce strategies without major changes to the original code
- There are many ways to deal with the same problem, only when the specific behavior is different
Reference article: JavaScript eliminates if else and switch with policy mode
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){ return strFunc[name]?strFunc[name]():0; } console.log(getData('add'));
proxy pattern
Control before accessing the main body and judge the content of the method
For example, you can access the login interface only after you click the data verification after login
const login(name){ console.log(name+'Logged in'); } const proxyCheckLogin(name){ if(!name)return login(name); }
Publish subscribe mode
One party publishes events and the other party subscribes to receive events
For example, vuex of vue and mobx|redux of react are all in this form
Disadvantages:
- Resident memory increases performance overhead
- As the project gets larger, it becomes more difficult to track subscriptions
Intermediary model
All methods are implemented through the mediator method. When the content changes, notify the mediator to change it
For example: extract the common part of the method into a separate function to call
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');
Decorator mode
Supplement and expand the content of existing objects or methods and endow them with more capabilities
For example: Xiao Ming used to eat only with chopsticks. After passing through the decorator, he learned to use knives and forks
function Person() {} Person.prototype.skill = function() { console.log('mathematics'); }; // Decorators and 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(); // mathematics person1.skill(); // Mathematical music
State mode
Encapsulation status. The status has been defined and the user does not need to know
For example: turn on the light, turn off the light, and only change the state through the state mode
Adapter mode
Adapt the unsuitable parts between methods
For example: foreach parses array data, but an object is passed in. At this time, it is necessary to judge and adapt
// Rendering data, the format is limited to array function renderData(data) { data.forEach(function(item) { console.log(item); }); } // Convert and adapt non array function arrayAdapter(data) { if (typeof data !== '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
Appearance mode
Define a function to store other functions, and then execute them uniformly
For example: just beautify
// Three processing functions function add() { console.log('add'); } function update() { console.log('update'); } // Appearance function, which unifies some processing to facilitate calling function execute() { add(); update(); } // Call init to start execution function init() { // High level functions are called directly here, or you can choose to call related functions directly over it execute(); } init(); // add update
Iterator mode
The iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing the internal representation of the object
No usage scenario
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) { return ret; } } } var temp=iteratorFunc(add,update);
Responsibility chain model
Call one by one until a function method processes the request
For example: similar to if/else
Template method pattern
Encapsulate subclass methods and guide subclasses in which order to execute which methods
Sharing element mode
Reduce the number of shared objects
Combination mode
It is to build larger objects with small sub objects, and these small sub objects themselves may be composed of smaller "grandchildren"
Command mode
A command is an instruction that performs certain things
Reference article: Fifteen common design patterns in JS