7 JavaScript Design Patterns

From: Micro reading https://www.weidianyuedu.com/content/4017485010725.html

It is appropriate for developers to use JavaScript Design Patterns as templates to solve problems, but it does not mean that these patterns can replace the work of developers.

Through design patterns, we can combine the experience of many developers to construct code in an optimized way, so as to solve the problems we face. Design patterns also provide a common vocabulary for describing problem solutions, rather than tediously describing the syntax and semantics of the code.

JavaScript Design patterns can help developers write orderly, beautiful and reasonably structured code. Although design patterns are easy to reuse, they are not intended to replace the work of developers; They are the support and assistance of developers and provide general solutions independent of specific applications, so as to avoid small vulnerabilities that may lead to major problems in the development of Web applications.

Our overall code base is more robust and eliminates unnecessary code duplication.

In this article, I will explore the seven best and most popular JavaScript Design Patterns, which are mainly divided into the following three categories: creative design pattern, structural design pattern and behavioral design pattern.

1. Constructor design pattern

This is a special method for initializing newly created objects after allocating memory. Because JavaScript is generally object-oriented, it deals with objects most. So I'm going to delve into object constructors. There are three ways to create a new object in JavaScript.

Here is a way to create a constructor design pattern.

// Create a new empty object var newobject = {}// Create a new empty object var newobject = object create(Object.prototype); var newObject = newObject();

To access the properties of a function, you need to initialize the object.

const object = new ConstructorObject();

The new keyword above tells JavaScript that a constructorObject should act as a constructor. This design pattern does not support inheritance.

2. Prototype mode

Prototype pattern is based on prototype inheritance. In this pattern, the created object acts as a prototype for other objects. In fact, a prototype is a blueprint for each object constructor that is created.

Examples

var myCar= {name:"Ford Escort",brake:function(){console.log("Stop! I am applying brakes");}Panic : function (){console.log ( "wait. how do you stop thuis thing?")}}// Use object create to implement a new instantiation carvar yourcar = object create(myCar);//  Now it is the prototype of another console log (yourCar.name);]

3. Module design mode

The module design pattern makes some improvements to the prototype pattern. Module mode sets different types of modifiers (private and public). You can create similar functions or properties without conflict. We can also flexibly expose renaming functions. One drawback of this design pattern is the inability to override functions created in the external environment.

Examples

function AnimalContainter () {const container = [];function addAnimal (name) {container.push(name);}function getAllAnimals() {return container;}function removeAnimal(name) {const index = container.indexOf(name);if(index < 1) {throw new Error("Animal not found in container");}container.splice(index, 1)}return {add: addAnimal,get: getAllAnimals,remove: removeAnimal}}const container = AnimalContainter();container.add("Hen");container.add("Goat");container.add("Sheep");console.log(container.get()) //Array(3) ["Hen", "Goat", "Sheep"]container.remove("Sheep")console.log(container.get()); //Array(2) ["Hen", "Goat"]

4. Singleton mode

This pattern is required when only one instance needs to be created (for example, a database connection). In this mode, only one instance can be created when the connection is closed, or the existing instance must be closed before opening a new instance. This pattern is also called strict pattern. One disadvantage of this pattern is that the test experience is very poor, because it is difficult to pick out the hidden dependency objects for testing.

Examples

function DatabaseConnection () {let databaseInstance = null;// Track the number of instances created at a specific time. let count = 0;function init() {console.log(`Opening database #${count + 1}`);//  Now execute the operation} function createinstance() {if (databaseinstance = = null) {databaseinstance = init();} return databaseInstance;} function closeIntance() {console.log("closing database");databaseInstance = null;} return {open: createIntance,close: closeIntance}}const database = DatabseConnection(); database. open(); // Open database #1database. open(); // Open database #1database. open(); // Open database #1database. close();  //close database

5. Factory mode

The innovation of this pattern is that it can create objects without constructors. It provides a common interface for creating objects, in which we can specify the type of factory object to be created. In this way, we only need to specify the object, and then the factory will instantiate and return the object for our use. When the setting of object components is very complex, and we want to easily create different object instances according to our environment, using factory mode is a wise choice. The factory pattern can also be used when dealing with many small objects that share the same attributes and creating some objects that need to be decoupled.

Examples

// Dealer ADealerA = {};DealerA.title = function title() {return "Dealer A";};DealerA.pay = function pay(amount) {console.log(`set up configuration using username: ${this.username} and password: ${this.password}`);return `Payment for service ${amount} is successful using ${this.title()}`;};//Dealer BDealerB = {};DealerB.title = function title() {return "Dealer B";};DealerB.pay = function pay(amount) {console.log(`set up configuration using username: ${this.username}and password: ${this.password}`);return `Payment for service ${amount} is successful using ${this.title()}`;};//@param {*} DealerOption//@param {*} configfunction DealerFactory(DealerOption, config = {}) {const dealer = Object.create(dealerOption);Object.assign(dealer, config);return dealer;}const dealerFactory = DealerFactory(DealerA, {username: "user",password: "pass"});console.log(dealerFactory.title());console.log(dealerFactory.pay(12));const dealerFactory2 = DealerFactory(DealerB, {username: "user2",password: "pass2"});console.log(dealerFactory2.title());console.log(dealerFactory2.pay(50));

6. Observer mode

The observer design pattern is convenient in scenarios where many objects communicate with other object sets at the same time. In observer mode, unnecessary events push and pull will not occur between states; In contrast, the modules involved only modify the current state of the data.

Examples

function Observer() {this.observerContainer = [];}Observer.prototype.subscribe = function (element) {this.observerContainer.push(element);}// The following is to remove an element observer from the container prototype. unsubscribe = function (element) {const elementIndex = this.observerContainer.indexOf(element);if (elementIndex > -1) {this.observerContainer.splice(elementIndex, 1);}}/***  we notify elements added to the container by calling* each subscribed components added to our container*/Observer. prototype. notifyAll = function (element) {this.observerContainer.forEach(function (observerElement) {observerElement(element);});}

7. Command mode

Finally, the command mode is introduced. The command design pattern encapsulates a method call, operation, or request into a single object so that we can pass the method call ourselves. The command design pattern allows us to issue commands from any command being executed and delegate responsibility to different objects. These commands are displayed in run() and execute() formats.

(function(){var carManager = {// Requested information requestinfo: function (model, ID) {return "the information for" + model + "with ID" + ID + "is foo bar";}// Now buy this carbuyvehicle: function (model, ID) {return "you have successfully purchased item" + ID + ", a" + model;}// Now arrange viewingarrangeviewing: function (model, ID) {return "you have successfully booked a viewing of" + model + "(" + ID + ")";}};}) ();

Small knot

For JavaScript developers, there are many benefits to using design patterns. Some of the main advantages of design patterns include improving the maintainability of the project and reducing unnecessary work in the development cycle. JavaScript Design patterns can provide solutions to complex problems, improve development speed and productivity.

Keywords: Javascript Programming ECMAScript

Added by DeltaRho2K on Sun, 06 Feb 2022 07:27:29 +0200