Creation pattern

The factory pattern

In factory mode, we create objects without exposing the creation logic to the client, and by using a common interface to point to newly created objects, it provides the best way to create objects. Personal understanding is similar to a factory floor that can produce specified products

Function example:

function factoryMode(name, age) { const obj = { name, age }; return obj; } const zs = factoryMode(' factoryMode ', 18); Const ls = factoryMode(' factoryMode ', 20)Copy the code

Constructor pattern

Call the constructor new fn() to return the object instance with the specified characteristics

There are similarities with factory mode, the differences are as follows:

1. There is no explicit creation object

2. Assign attributes and methods directly to this

3. No return statement

New does the following four steps

Create a new object

2. Assign the constructor’s scope to the new object (thus this refers to the new object)

3. Execute the code in the constructor (add attributes to this new object)

4. Return a new object

Function example:

function ConstructorMode(name, age) { this.name = name; this.age = age; }; Const zs = new ConstructorMode(' sz ', 18); Const ls = New ConstructorMode(' ConstructorMode ', 20)Copy the code

The prototype pattern

Prototype patterns are used to create repetitive objects while maintaining performance. It provides an optimal way to create objects.

Public methods and attributes are put on the prototype to avoid repeated definition and facilitate maintenance

function PrototypeMode(name, age) { this.name = name; this.age = age; } PrototypeMode.prototype.sayName = function () { console.log('my name is', this.name); } const zs = new PrototypeMode(' sz ', 18); Const ls = new PrototypeMode(' PrototypeMode ', 20); zs.sayName(); ls.sayName();Copy the code

The singleton pattern

This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique objects directly, without instantiating the objects of the class, and provides an optimal way to create objects.

Funciton example function:

function singletonMode(name, age) { let instance = {}; return function (name, age) { if (! instance.name) { instance.name = name; instance.age = age; } return instance; } } const instance = singletonMode(); Const zs = instance(' sz ', 18); Const ls = instance(' li si ', 20); console.log(zs === ls); // trueCopy the code

Class example:

class SingletonModeClass { static instanceClass = {}; constructor(name, age) { if (! this.constructor.instanceClass.name) { this.constructor.instanceClass.name = name; this.constructor.instanceClass.age = age; } return this.constructor.instanceClass; }} const zs2 = new SingletonModeClass(' zhang3 ', 18); Const ls2 = new SingletonModeClass(' lI ', 20); console.log(zs2 === ls2); // trueCopy the code

Structural mode

Decorator pattern

The Decorator Pattern allows you to add new functionality to an existing object without changing its structure. That is, to attach functionality to an object without changing the original object

Function example:

Function Dog() {this.name = 'black '; this.age = 2; This. Skill = function () {console.log(' woo woo woo '); } } const xiaohei = new Dog(); function addWalk(dog) { const skill = dog.skill; dog.skill = function () { skill(); Console. log(' I can go '); }}; addWalk(xiaohei); function addRun(dog) { const skill = dog.skill; dog.skill = function () { skill(); Console. log(' I can run '); }}; addRun(xiaohei); xiaohei.skill();Copy the code

The proxy pattern

In the Proxy Pattern, one class represents the functionality of another class.

Intent: Provide a proxy for other objects to control access to this object.

That is, to access an object, not directly to the object, but to access its proxy object, through the proxy object pre-processing business logic, and then inform the proxy object

advantages

1. Clear responsibilities

2. High scalability

3. Objects can be protected

4. Optimize performance, reduce overhead objects, and cache results

ES6 proxy example:

Const person = {name: "zhang3 ", age: 18}; const proxy = new Proxy(person, { get: function (target, propKey, receiver) { console.log(target, propKey, receiver); if (propKey in target) { return target[propKey]; } else {throw new ReferenceError(' no ${propKey} property '); } }, set: function (target, propKey, value, receiver) { console.log(target, propKey, value, receiver); Console. log(' ${propKey} property is set to 20 '); target[propKey] = 20; }}); Sex Uncaught ReferenceError: No sex proxy.age = 100 Age was set to 20Copy the code

For example, a lot of celebrity affairs are handled by agents, such as buying things, whether to accept a certain endorsement and so on

Const Shoes = function (name) {this.name = name; const Shoes = function (name) {this.name = name; }; Shoes.prototype.getName = function () { return this.name; }; Prototype. Business = function () {const curTime = new Date().gethours (); return curTime >= 8 && curTime <= 20 ? ${this.getName()} ':' Non-business hours! '; } // define a const assistant = {buyShoes: function (shoes) {star.buyshoes (shoes.business()); }, pickUpWork: function (work) {if (work.amt < 100000) {star.pickupwork (' < 100000 ')} else if (! Work.brand.includes (' China ')) {star.pickupwork (' China ')} else { Star.pickupwork (' pick up a ${work.brand} activity, appearance fee ${work.amt} ')}}}; Const star = {buyShoes: function (res) {console.log(res); }, pickUpWork: function (res) { console.log(res); }}; BuyShoes (new Shoes(' crocodile Shoes ')); / / bought a pair of alligator shoes | | the non-operating time! PickUpWork ({amt: 100, brand: 'Li Ning China'}); PickUpWork ({amt: 1000000, brand: 'Nike'}); PickUpWork ({amt: 1000000, brand: 'Li Ning China'}); // Accepted an event of Li Ning China, with an appearance fee of 1,000,000 yuanCopy the code

In addition, there is a large blank space before loading a large image. In this case, loading map or placeholder map should be displayed, or the idea of proxy mode can be used to complete the loading map, as follows:

Const myImage = (function () {// create dom const imgNode = document.createElement('img'); document.body.appendChild(imgNode); return { setSrc: function (src) { imgNode.src = src; }}}) (); Const preImage = (function () {dom const img = new Image(); // Replace SRC img.onload = function () {myimage.setsrc (img.src); }; Return {/ / dom first to set loading pictures setSrc: function (SRC) {myimage.png setSrc (' https://z3.ax1x.com/2021/03/29/cCjyPf.png '); // Set img. SRC = SRC; }}}) (); preImage.setSrc('https://s1.ax1x.com/2020/05/09/YlFytA.jpg');Copy the code

Adapter mode

The Adapter Pattern acts as a bridge between incompatible interfaces and combines the functionality of two separate interfaces, just like a common MAC Adapter. The following is an example:

GetInterface () {return 'Mac interface '; Constructor () {this.macinstance = new Mac(); } transfer () {/ / access to conversion interface const MacInterface = this. MacInstance. GetInterface (); Return 'convert ${MacInterface} to a generic interface'}} // instantiate converter const Converter = new Converter(); // Call the conversion function console.log(Converter.transfer ()); // Convert the Mac interface to a generic interfaceCopy the code

Behavioral pattern

Observer model

The Observer Pattern is used when there is a one-to-many relationship between objects. For example, when an object is modified, dependent objects are automatically notified.

Class example:

Update class Subject {constructor() {this.count = 0; // Observer set this.obServerList = []; } state getCount() {return this.count; } // setState setState(count) {this.count = count; this.notifyAllObservers(); } // addObserver addObserver(observer) {this.observerlist.push (observer); } / / notify observers update notifyAllObservers () {this. ObserverList. ForEach (observer = > {observer. The update (); Update class Observer {constructor(name, subject) {this.name = name; // This. Subject = subject; // Add this to the observer this.subject.addobServer (this); Update () {console.log(' ${this.name} update,count=${this.subject.getCount()} ')}} let subjectObj = new Subject(); let observer1 = new Observer('observer1', subjectObj); let observer2 = new Observer('observer2', subjectObj); subjectObj.setState(1); subjectObj.setState(2);Copy the code

The above is a personal summary of the JS design mode, if there are mistakes or not rigorous place, please give correction, thank you very much!