A design pattern should include the following elements

Schema Name Description Context Outline Problem statement Solution design implementation illustration example auxiliary condition relation known usage discussion

Give explanations and case studies directly to help understand

Constructor pattern

A constructor is a special method used to initialize a new object if memory has been allocated to the object
  1. The base Constructor

    function Person(name,age,sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.personalString = function() {return 'Name:'+ this.name + ' 年龄:' + this.age + 'Gender:'+ this.sex } } <! --example--> var xiaoming = new Person('Ming'.'18'.'male'); console.log(xiaoming.personalString()) <! ---- Name: Xiaoming Age: 18 Gender: Male >Copy the code

    Disadvantages: Base constructor inheritance becomes difficult

  2. Constructor with prototype

    function Person(name,age,sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    Person.prototype.personalString = function() {return 'Name:'+ this.name + ' 年龄:' + this.age + 'Gender:'+ this.sex } <! --example--> var xiaoming = new Person('xiaoling.'17'.'woman'); console.log(xiaoming.personalString()) <! ---- Name: Xiaoling Age: 17 Gender: female >Copy the code

The constructor pattern uses the new keyword to create different examples where __proto__. Contructor points to the same constructor xiaoming.__proto__. Constructor === Person



The module pattern

Module was originally an approach to traditional software engineering that encapsulated private and public methods for classes
var countModule = (function(){
    var counter = 0;
    return {
        add:function() {return ++counter;
        },
        min:function() {return --counter;
        }
    }
})();
<!--example-->
countModule.add() //--> 1
countModule.add() //--> 2
countModule.min() //--> 1
Copy the code
var myModule = (function(){
    var module = {},
        privateVariable = "hello world";
    function privateMethod(){
        
    }
    module.publicProperty = "Foobar";
    module.publicMethod = function(){
        console.log(privateVariable);
    };
    return module;
})
Copy the code

Declare the object, mount the register, return the output directly, and reassign the value to mount the declared global variable

Understanding: Use closures to maintain private variables, prevent contamination of global scope, and isolate reference conflicts with other developers



The proxy pattern

Provides a proxy or placeholder for an object to control access to it. For example picture lazy load business model
var imgFunc = (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() {
        imgFunc.setSrc(this.src);
    }
    return {
        setSrc: function(src) {
            imgFunc.setSrc('./loading,gif'); img.src = src; }}}) (); proxyImage.setSrc('./pic.png');
Copy the code


The singleton pattern

The singleton pattern is defined to ensure that a class has only one instance and provides a global access point to access it. This ensures that a class has only one instance object, by checking if the instance exists and returning if it does, or by creating and returning if it does not.
class CreatePerson {
    constructor(name) {
        this.name = name;
        this.getName();
    }
    getName() {
         returnthis.name; } Person = () {Person = ();function() {
    var instance = null;
    return function(name) {
        if(! instance) { instance = new CreatePerson(name); }return instance;
    }
})();

// test
var a = new Person("aaa");
var b = new Person("bbb");

console.log(a === b);    
//true
Copy the code


Observer model

One or more observers interested in a target state register by associating themselves with the target. An alert message is sent when there is a change to the target that might be of interest to the observer, which in turn invokes the update method for each observer. If the observer is no longer interested in the target state, it simply needs to disassociate.
1. The Subject

Maintains a series of observers to easily add or remove observers
Observer 2

Provides an update interface for objects that need to be notified when the target state changes
ConcreteSubject Concrete goals

When the status changes, theObserverSend notifications, storeConcreteSubjectstate
4.ConcreteObserver

Store a pointer toConcreteSubjectDrink, achieveObserverUpdate interface to ️ to keep its state consistent with that of the target
function Tweeter () {
    var subject = new Subject();
    this.addObserver = function (observer) {
        subject.add_observer(observer);
    };
    this.removeObserver = function (observer) {
        subject.remove_observer(observer);
    };
    this.fetchTweets = function fetchTweets () {
        // tweet
        var tweet = {
            tweet: "This is one nice Observer"}; // Notify the observer of changes subject.notify(tweet); }; } // Add observer var TweetUpdater = {update:function () {
        console.log('Update Tweet - ', arguments); }}; var TweetFollower = { update:function () {
        console.log('Following this tweet - ', arguments); }}; var tweetApp = new Tweeter(); tweetApp.addObserver(TweeterUpdater); tweetApp.addObserver(TweeterFollower); tweetApp.fetchTweets(); tweetApp.removeObserver(TweetUpdater); tweetApp.removeObserver(TweetFollower);Copy the code


Mixins mode

Mixins can be used if you have functionality that can be shared across multiple object and class hierarchies; If the functionality to be shared is in a single level, you can use inheritance. In stereotype inheritance, if inheritance comes from a stereotype, changes made to the stereotype affect everything inherited from the stereotype. If you don’t want this to happen, you can use mixins
var _ = require('underscore'); // Encapsulate shared functionality in CustomLoggerfunction () {
    var CustomLogger = {
        log: function(message) { console.log(message); }};returnCustomLogger}()) // the object that needs a CustomLogger to record system-specific logs var Server = (function (Logger) {
    var CustomServer = function () {
        this.init = function () {
            this.log("Initializing Server..."); }; }; // Copy/extend the members of CustomLogger to customServer_.extend (CustomServer. Prototype, Logger);return CustomServer;
}(logger));

(new Server()).init();
Copy the code


The prototype pattern

Use prototype instances to point to the type of object to be created, and create new objects by copying these prototypes
function Person () {
  this.name = 'ivan'
  this.sex = '28'
  this.age = 'male'
  this.getName=function () {
    return` name:${this.name}`
  }
}
Person.prototype.getInfo = function () {
  return` name:${this.name}Age:${this.age}Gender:${this.sex}`}let person = new Person()

const person1 = Object.create(proto)
const person2 = Object.create(proto)

person1.name //"ivan"
person2.name //"ivan"

person1.name = 'xxx' // "xxx"
person2.name   //"ivan"
Copy the code


Command mode

Encapsulate method call request operations into a single object to parameterize clients and pass method calls available for execution based on our different requests. In addition, this pattern decouples the object that invokes the operation from the object that knows how to implement it, and provides greater overall flexibility in swapping out concrete classes.

* Reduce coupling to a degree of OOP compliance by assuming Bridges
let CarManager = (() => {
  return {
    requesrInfo: (model, id) =>{
      return 'The information for ' + model + 'width ID' + id + 'is foobar'
    },
    buyVehicle: (model, id) =>{
      return 'purchased Item ' + model + ', ' + id
    },
    arrangeView: (model, id) =>{
      return 'You have successfully booked a viewing of ' + model + ' '+ id }, execute: (... arg) => {return CarManager[arg[0]] && CarManager[arg[0]].apply(CarManager,[].slice.call(arg,1))
    }
  }
})()

CarManager.execute('arrangeView'.'ff'.'123')
Copy the code


The appearance model

Provide a convenient high-level interface for larger code bodies that can hide the underlying complexity and be understood as a library API
let module = (() => {
  let _private = {
    i: 5,
    get: () => {
      console.log(this.i)
    },
    set: (val)=> {
      this.i = val
    },
    run: () => {
      console.log('runing')
    },
    jump: ()=> {
      console.log('jumping')}}return {
    facade: (args)=>{
      _private.set(args.val);
      _private.get();
      if(args.run){
        _private.run()
      }
    }
  }
})()

module.facade({run:true,val:10}) // 10 runing
Copy the code


The factory pattern

Interface for creating objects. Depending on the type passed into the factory, objects of a specific type can be created. A common implementation of this pattern is usually using classes or static methods of classes
class UserPerson {
  constructor(name = ' ', task = ' ') {
    this.name = name
    this.task = task
  }
}

class userPersonFactory extends UserPerson {
  constructor(name, viewPage) {
    super(name, viewPage)
  }
  create(role) {
    switch (role) {
      case 'teacher': 
        return new userPersonFactory( 'the teacher'.'teach' );
        break;
      case 'student':
        return new userPersonFactory( 'students'.'learning' );
        break
      default:
        throw new Error('Can't find what you want')}}}let UPF = new userPersonFactory()
let teacher = UPF.create('teacher')
// userPersonFactory {name: "Teacher", task: "Teaching"}
let student = UPF.create('student')
// userPersonFactory {name: "Students", task: "Learning"}
let principal = UPF.create('principal') // Uncaught Error: Cannot find what you wantCopy the code

If you have any questions, please comment on them. Special thanks to !!!!!!