Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common design patterns of JavaScript5?

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the common design patterns of JavaScript5". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the common design patterns of JavaScript5?"

Definition of design patterns

Design pattern is a concise and elegant solution to specific problems in the process of object-oriented software design. The implementation of design patterns may actually be different in different programming languages. For example, java and javascript, in a statically compiled language like Java, cannot dynamically add responsibilities to existing objects, so the decorator pattern is generally implemented by wrapping classes. But in a dynamically interpreted language like JavaScript, it's easy to add responsibilities to objects dynamically. As a result, the decorator pattern of the JavaScript language is no longer focused on dynamically adding responsibilities to objects, but on dynamically adding responsibilities to functions.

I. Factory model

Factory pattern is one of the most commonly used design patterns used to create objects. Instead of exposing the specific logic of creating objects, the logic is encapsulated in a function, which can be regarded as a factory. Factory patterns can be divided into simple factories, factory methods and abstract factories according to the degree of abstraction. Next, we will give a simple example of the application of simple factories and factory methods in JavaScript:

1. Simple factory

The simple factory pattern, also known as the static factory pattern, is determined by a factory object to create an instance of a product object class, which is mainly used to create the same kind of object.

For example, in actual projects, we often need to render different pages according to the user's permissions, and some pages owned by users with high-level permissions cannot be viewed by users with low-level privileges. So we can save the pages that the user can see in the constructor of users with different permission levels.

Let UserFactory = function (role) {function SuperAdmin () {this.name = "Super Admin", this.viewPage = ['Home', 'user Management', 'order Management', 'Application Management', 'Rights Management']} function Admin () {this.name = "Administrator", this.viewPage = ['Home', 'order Management' Function NormalUser () {this.name = 'normal user', this.viewPage = ['Home', 'order Management']} switch (role) {case 'superAdmin': return new SuperAdmin () Break; case 'admin': return new Admin (); break; case' user': return new NormalUser (); break; default: throw new Error ('parameter error, optional parameters: superAdmin, admin, user');}} / / call let superAdmin = UserFactory (' superAdmin'); let admin = UserFactory ('admin') let normalUser = UserFactory (' user')

Summary: in the above example, UserFactory is a simple factory. In this function, there are three constructors corresponding to users with different permissions. When we call the factory function, we only need to pass one of the three optional parameters, superAdmin, admin, user, to get the corresponding instance object.

Advantages: the advantage of a simple factory is that you only need one correct parameter to get the object you need without knowing the details of its creation.

Disadvantages: the creation logic (constructor) and judgment logic code of all objects are included in the function. Every time a new constructor is added, the judgment logic code needs to be modified. When our objects are not the above three, but 30 or more, this function will become a huge super function, so it will be difficult to maintain. A simple factory can only act on a small number of objects created. When the creation logic of an object is not complex, use the

two。 Factory method

The original intention of the factory method pattern is to defer the actual creation of the object to the subclass, so that the core class becomes an abstract class, but it is difficult to create an abstract class like the traditional object-oriented in JavaScript, so in JavaScript we only need to refer to its core idea, and we can think of the factory method as a factory class that instantiates objects.

For example, in the above example, we can use the factory method to write like this, the factory method we only think of it as a factory for instantiating objects, it only does the thing of instantiating objects, and we use safe mode to create objects.

/ / the factory method function created by security mode let UserFactory = function (role) {if (this instanceof UserFactory) {var s = new this [role] (); return s;} else {return new UserFactory (role) }} / / the constructor for all objects is set in the prototype of the factory method function UserFactory.prototype = {SuperAdmin: function () {this.name = "Super Admin", this.viewPage = ['Home', 'user Management', 'order Management', 'Application Management', 'Rights Management']}, Admin: function () {this.name = "Administrator", this.viewPage = ['Home Page' 'order management', 'application management']}, NormalUser: function () {this.name = 'ordinary user', this.viewPage = ['home', 'order management']}} / / call let superAdmin = UserFactory ('SuperAdmin') Let admin = UserFactory ('Admin') let normalUser = UserFactory (' NormalUser')

Summary: in a simple factory, if we add a new user type, we need to modify the code in two places, one is to add a new user constructor, the other is to add a judgment to the new user in the logical judgment, while in the abstract factory method, we only need to add it in the UserFactory.prototype.

2. Singleton model

Definition: ensures that there is only one instance of a class and provides a global access point to it.

Requirements: we often only need one object, such as thread pool, global cache, window object in browser, login float, etc.

Implementation: use a variable to identify whether an object has currently been created for a class, and if so, return the previously created object directly the next time you get an instance of the class.

Advantages:

Can be used to divide namespaces and reduce the number of global variables

Can be instantiated, and instantiated once, instantiated again will generate * instances.

As an example, in js, we can use closures to create and implement this pattern:

Var single = (function () {var unique; function getInstance () {/ / if the instance exists, return it directly, otherwise instantiate if (unique = undefined) {unique = new Construct ();} return unique;} function Construct () {/ /. The code to generate the singleton constructor} return {getInstance: getInstance}}) ()

Summary: in the above code, we can use single.getInstance to get the singleton, and each call gets the same singleton. In our usual development, we often use this mode. For example, when we click the login button, a login box appears on the page, and the floating window is unique. No matter how many times the login button is clicked, the floating window will only be created once. Therefore, this login floating window is suitable for singleton mode.

Third, agency mode

The proxy pattern mainly provides a proxy for other objects to control access to this object, and mainly solves the problems caused by direct access to the object, for example, the object to be accessed is on a remote machine, in an object-oriented system, some objects are due to some reasons (for example, object creation is expensive, or some operations require security control, or require out-of-process access). Direct access can bring a lot of trouble to the user or system structure, and we can add an access layer to this object when we access this object.

The most basic form of proxy pattern is to control access. The proxy object and another object (ontology) implement the same interface. In fact, the work is still done by the ontology. It is the object or class responsible for performing the assigned task. The proxy object does nothing more than control access to the ontology, and the proxy object does not add or modify its methods on the basis of another object. Nor will it simplify the interface of that object, it implements exactly the same interface as the ontology, and all method calls to it are passed to the ontology.

(function () {/ / sample code / / target object, which is the object function Subject () {} Subject.prototype.request = function () {}; / * proxy object * @ param {Object} realSubject [holds the specific target object of the proxy] * / function Proxy (realSubject) {this.realSubject = readSubject;} Proxy.prototype.request = function () {this.realSubject.request ();} } ())

Summary: in the above code, Proxy can control access to the real proxied object. In proxy mode, the more common is the virtual proxy, which is used to control access to the ontology that is expensive to create. It will postpone the instantiation of the ontology until a method is called. For example, we assume that the instantiation of PublicLibrary is slow and cannot be completed immediately when the web page is loaded. We can create a virtual proxy for it and ask it to postpone the instantiation of PublicLibrary until necessary. For example, we can use a virtual proxy for lazy loading of pictures that we often use in the front end.

IV. Observer model

If you have learned some frameworks like vue,react, I believe you must be familiar with the Observer pattern. Now many mvvm frameworks use the idea of Observer pattern, which is also called publish-subscribe pattern. It defines an one-to-many dependency between objects. When the state of an object changes, all objects that depend on it will be notified and updated. The Observer pattern provides a subscription model in which objects subscribe to events and are notified when they occur. This pattern is the cornerstone of event-driven programming and is beneficial to good object-oriented design.

Definition: an one-to-many dependency between objects.

Requirements: when the state of an object changes, all objects that depend on it will be notified.

Advantages: decoupling in time, decoupling between objects.

Achieve:

Specify who will act as the publisher

Add a cache list to the publisher to store the callback function to notify the subscriber

When the message is published, the publisher traverses the cache list and in turn triggers the subscriber callback function stored in it.

For example, if we bind an event to a dom node on the page, we can actually think of it as an observer mode:

Document.body.addEventListener ("click", function () {alert ("Hello World")}, false) document.body.click () / / simulated user click

Summary: in the above example, we need to monitor the user's click on document.body, but we have no way to predict when the user will click, so we subscribe to document.body 's click event. When the body node is clicked, the body node will post a "Hello World" message to the subscriber.

Fifth, strategic model

Policy pattern refers to defining a series of algorithms and encapsulating them one by one. The purpose is to separate the use of the algorithm from the implementation of the algorithm, avoid multiple judgment conditions, and be more scalable.

The following is also an example. At present, there are activities in the supermarket. Vip is 50% discount, regular customers 70% discount, ordinary customers do not discount, calculate the amount that * needs to pay. If we do not use the policy mode, our code may be the same as below:

Function Price (personType, price) {/ / vip 50% discount if (personType = = 'vip') {return price * 0.5;} else if (personType = =' old') {/ / regular customer 70% discount return price * 0.3;} else {return price; / / other all full price}}

In the above code, we need a lot of judgments. If there are a lot of discounts, we need to add a lot of judgments. This has violated the opening and closing principle of the six principles of the design pattern just mentioned. If we use the strategy pattern, our code can be written as follows:

/ / for vip customers function vipPrice () {this.discount = 0.5;} vipPrice.prototype.getPrice = function (price) {return price * this.discount;} / / for regular customers function oldPrice () {this.discount = 0.3;} oldPrice.prototype.getPrice = function (price) {return price * this.discount;} / / for regular customers function Price () {this.discount = 1 } Price.prototype.getPrice = function (price) {return price;} / / context, for client use function Context () {this.name =''; this.strategy = null; this.price = 0;} Context.prototype.set = function (name, strategy, price) {this.name = name; this.strategy = strategy; this.price = price } Context.prototype.getResult = function () {console.log (this.name + 'checkout price is:' + this.strategy.getPrice (this.price));} var context = new Context (); var vip = new vipPrice (); context.set ('vip customer', vip, 200); context.getResult (); / / vip customer checkout price is: 100 var old = new oldPrice (); context.set ('regular customer', old, 200); context.getResult () / / regular customer's checkout price is: 60 var Price = new Price (); context.set ('ordinary customer', Price, 200); context.getResult (); / / ordinary customer's checkout price is: 200. so far, I believe everyone has a deeper understanding of "what is the common design pattern of JavaScript5". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report