1. Singleton mode

Only one instance of a class can be created. Code implementation ideas: first determine whether to create an instance, create a direct return, not create an instance, and return

class Person {
    constructor (name) {
        this.name = name
    }
}
Person.getInstance = function (name) {
    if (this.instance) {
        return this.instance
    }else {
        return this.instance = new Person(name)
    }
}
Copy the code

Function: communication before module, ensure a unique instance of a class

Application Scenarios:

  • Click a button to pop up the login box, each click can only pop up one

Code implementation

<button id=' BTN '> </button> js: class LoginLayer { constructor () { this.instance = null this.init() } init () { let ele = document.createElement('div') Ele. ClassList. Add (' loginLayer) ele. InnerHTML = "login bounced" document. The body. The appendChild (ele)} the static getInstance () {if (this.instance) return this.instance this.instance = new LoginLayer() return this.instance; } } let btn = document.getElementById('btn') btn.addEventListener('click', _ => { LoginLayer.getInstance() }, false)Copy the code
  • There is only one vuex store globally
function install (_Vue) { if (Vue && _Vue === Vue) { { console.error( '[vuex] already installed. Vue.use(Vuex) should be  called only once.' ); } return } Vue = _Vue; applyMixin(Vue); }Copy the code

2. Constructor pattern

Used to create specific types of objects for reuse of complex business logic and functionality

  • Create one instance after another without affecting each other
  • Logic and functionality are reusable
class Person {
	construcotr (name) {
    	this.name = name
    }
    getName () {
    	return this.name
    }
}
Copy the code

3. Builder mode

Take complex logic step by step and implement it methodically

4. Proxy mode

One object controls access to another object through some kind of proxy

Function:

  • Cache proxy (if the computation cost is high, cache is provided, and the same calculation is performed next time without recalculation)
function sum(a, b){
  return a + b
}
let proxySum = function() {
  let cache = {}
  return function () {
    let argStr = Array.prototype.join.call(arguments)
    if (argStr in cache) {
      return cache[argStr]
    }
    cache[argStr] = sum.apply(this, arguments)
    return cache[argStr]
  }
}
Copy the code
  • Secure proxy (restricting access to the original object)
  • Virtual proxy (render a large image of a web page, you can use thumbnails first)
var myImage = (function(){ var imgNode = document.createElement( 'img' ); document.body.appendChild( imgNode ); return { setSrc: function( src ){ imgNode.src = src; }}})() var proxyImage = (function(){var img = new Image(); img.onload = function(){ myImage.setSrc( this.src ) } return { setSrc: function( src ){ myImage.setSrc(defaultUrl) img.src = src; } } })() proxyImage.setSrc(url)Copy the code
  • Remote agent

5. Appearance mode

The facade pattern defines a high-level interface that makes this subsystem easier to use

  • Simplifying complex interfaces
  • Decoupled and shielded the direct access of the consumer to the subsystem
function a(x){
   // do something
}
function b(y){
   // do something
}
function ab( x, y ){
    a(x);
    b(y);
} 
Copy the code

Application scenarios

We can use the facade pattern to design methods that are compatible with event bindings across browsers and other methods or abstract classes that require a unified implementation interface.

Function on (type, fn) {/ / for event handler if support dom2 level (document. AddEventListener) {dom. AddEventListener (type, fn, false); }else if(dom.attachevent){// For Internet Explorer 9, dom.attachevent ('on'+type,fn); }else { dom['on'+ type] = fn; }}Copy the code

6. Observer mode – VUE

All observers listen to an object, and when the object changes, all observers are notified so that the observers can self-update

class Subject { constructor () { this.subs = [] } addSub (sub) { if (this.subs.indexOf(sub) === -1) { this.subs.push(sub) } } nodify () { this.subs.forEach(sub => sub.update()) } } class Observer { constructor (observerName) {this.observername = observerName} update () {console.log(' notifies ${this.observername}, Let sub = new Observer('o1') let o2 = new Observer('o2') sub.addsub (o1) sub.addSub(o2)Copy the code

7. Release the subscriber model

It is a subset of the observer mode. The difference is that the observer is attached to the observed; Publish subscribe no, they have public Bridges

let pubsub = {}; (function(pubsub) { let callbacks = [] let results = [] // publisher pubsub.publish = function (data) { results.push(data) callbacks.forEach(c => c(results)) } pubsub.subscribe = function (callback) { Subscribe ((data) => {if (data.length === 3) {console.log('data length = 3')} Publish (3) publish(3) pubsub.publish(3) publish(3) pubsub.publish(3)Copy the code

8. Strategic mode

The strategy mode classifies and encapsulates different algorithms properly so that different algorithms can be replaced without affecting the users of the algorithm

  • Realization is different, action is consistent
  • The invocation is the same, reducing the cost of use and coupling between different algorithms
  • Define algorithm model separately to facilitate unit testing
  • Avoid a lot of redundant code judgments, such as if else, etc
const obj = {
  A: (num) => num * 4,
  B: (num) => num * 6,
  C: (num) => num * 8
}

const getSum =function(type, num) {
  return obj[type](num)
}
Copy the code