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 design patterns for Web development?

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

Share

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

This article mainly explains "what are the design patterns for Web development". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "what are the design patterns for Web development?"

What is a design pattern?

Design pattern is a general solution to some kinds of problems that occur repeatedly in the process of software design and development. Design patterns are more of a guiding ideology and methodology than ready-made code, and of course each design pattern has a specific implementation in each language. Learning design patterns is more about understanding the inner ideas of various patterns and solving problems. After all, this is the best practice summed up by countless previous experiences, while code implementation is an aid to deepening understanding. Design patterns are used to reuse code, make it easier for others to understand, and ensure code reliability. In this article, I will introduce five common design patterns that are actually used in JavaScript:

Singleton design pattern

Define

Singleton mode only allows a class or object to have a single instance, and it uses global variables to store that instance.

The implementation method is to determine whether an instance of the object exists, and if it already exists, it will no longer be created.

Usage scenarios are suitable for only one instance in a business scenario, such as pop-up windows and shopping carts.

Realize

The singleton model can be divided into lazy type and hungry type:

Lazy style

Let ShopCar = (function () {let instance; function init () {/ * the singleton code * / return {buy (good) {this.goods.push (good);}, goods: [],};} return {getInstance: function () {if (! instance) {instance = init ();} return instance },};}) (); let car1 = ShopCar.getInstance (); let car2 = ShopCar.getInstance (); car1.buy ('orange'); car2.buy ('apple'); console.log (car1.goods); / / ['orange', 'apple'] console.log (car1 = car2); / / true

Hungry Han style

Var ShopCar = (function () {var instance = init (); function init () {/ * the singleton code * / return {buy (good) {this.goods.push (good);}, goods: [],};} return {getInstance: function () {return instance;},};}) (); let car1 = ShopCar.getInstance () Let car2 = ShopCar.getInstance (); car1.buy ('orange'); car2.buy ('apple'); / / ['orange', 'apple'] console.log (car1.goods); console.log (car1 = car2); / / true

Lazy type does not create an instance when the class is loaded, so the class loads quickly, but the runtime gets the object slowly.

The hungry Chinese type completes the initialization when the class is loaded, so the class loads slowly, but the speed of getting the object is fast.

Strategy mode

Define

The policy pattern defines a series of algorithms that encapsulate each algorithm and allow them to replace each other.

The implementation method defines a set of variable policy classes to encapsulate specific algorithms, and defines a set of immutable environment classes to delegate the request to a policy class.

Usage scenarios are suitable for business scenarios where you need to judge a variety of conditions, even if complex conditions are nested. You can use policy patterns to improve the maintainability and readability of the code. Such as payment and blog permission verification.

Realize

Example:

/ / define several policy classes var PaymentMethodStrategy = {BankAccount: function (money) {return money > 50? Money * 0.7: money;}, CreditCard: function (money) {return money * 0.8;}, Alipay: function (money) {return money;},}; / * Environmental class * / var userPay = function (selectedStrategy, money) {return PaymentMethodStrategy [selectedStrategy] (money);}; console.log ('bank card payment price is:' + userPay ('BankAccount', 100)) / 70 console.log ('Alipay price:' + userPay ('Alipay', 100)); / 100 console.log (' credit card payment price:'+ userPay ('CreditCard', 100)); / / 80

Observer mode

Define

The observer pattern is the behavior pattern of objects, which defines an one-to-many dependency between objects, that is, the relationship between multiple observers and one observed. When the observed changes, it informs all the observer objects, and they do the corresponding operations.

The implementation method defines a set of variable policy classes to encapsulate specific algorithms, and defines a set of immutable environment classes to delegate the request to a policy class.

The usage scenario is suitable for business scenarios when the state of an object changes, you need to automatically notify other associated objects, automatically refresh the status of the object, or execute the corresponding object, for example, you are a teacher. When you need to notify the parents of the class, you can set up a group (list). Every time you notify an event, just loop through the list (mass send), regardless of who is on the list.

Realize

Example:

/ / create a group, save the notification, notify each parent (triggering all observer objects) class Group {constructor () {this.message ='no notification yet'; this.parents = [];} getMessage () {return this.message;} setMassage (message) {this.message = message; this.notifyAllObservers () } notifyAllObservers () {this.parents.forEach ((parent) = > {parent.update ();});} attach (parent) {this.parents.push (parent);}} / / Observer, each parent class Parent {constructor (name, group) {this.name = name; this.group = group; this.group.attach (this) } update () {console.log (`${this.name} receive notification: ${this.group.getMessage ()}`);}} let group = new Group (); let T1 = new Parent ('Mama Li', group); let T2 = new Parent ('Papa Wang', group); let T3 = new Parent ('Grandpa Zhang', group); group.setMassage ('parents' meeting'); group.setMassage ('hold the Games') / * Mother Li received notice: father Wang received notice: hold parent-teacher meeting Grandpa Zhang received notice: mother Li received notice: father Wang received notice: hold sports meeting Grandpa Zhang received notice: hold sports meeting * /

Publish and subscribe model

Define

Publish / subscribe mode means that the object that wants to receive notification (Subscriber) subscribes to the topic through custom events based on a topic, and the object that publishes the event (Publisher) notifies each Subscriber object subscribing to the topic by publishing the topic event.

Realize

Const pubSub = {list: {}, subscribe (key,fn) {/ / subscribe to if (! this.list [key]) {this.list [key] = [];} this.list [key] .push (fn);}, publish () {/ / publish const arg = arguments; const key = Array.prototype.shift.call (arg); const fns = this.list [key] If (! fns | | fns.length {console.log ('your sex is' + sex);}); / / publish pubSub.publish ('name',' ttsy1'); / / your name is ttsy1 pubSub.publish ('sex',' male'); / / your sex is male

The subscription of the above code is based on name and sex topics to customize events, and publishing is through name and sex topics and passing in parameters of custom events, eventually triggering custom events for a specific topic.

You can unsubscribe from a specific topic through the unSubscribe method.

PubSub.subscribe ('name', (name) = > {console.log (' your name is'+ name);}); pubSub.subscribe ('sex', (sex) = > {console.log (' your sex is'+ sex);}); pubSub.unSubscribe ('name'); pubSub.publish (' name', 'ttsy1'); / / this topic is unsubscribed to pubSub.publish (' sex', 'male'); / / your sex is male

Observer mode VS publish and subscribe model:

Both the Observer pattern and the publish-subscribe pattern define an one-to-many dependency and perform updates when the relevant state changes.

The difference is that a series of Subject objects that depend on Observer objects in Observer mode can only execute the same specific update method after being notified, while in publish / subscribe mode, different custom events can be executed based on different topics.

Relatively speaking, the publish-subscribe model is more flexible than the observer model.

Decorator mode

Define

On the basis of not changing the original structure and function, dynamically decorate some methods or properties suitable for the special scene, that is, add some new functions to enhance its ability.

The implementation method defines a set of variable policy classes to encapsulate specific algorithms, and defines a set of immutable environment classes to delegate the request to a policy class.

Use the original method of the scenario to remain unchanged, and then mount other methods on the original method to meet the existing needs; the decoupling of the function splits the function into multiple reusable functions, and then mounts the split function to a function to achieve the same effect but enhance reusability. Such as porous sockets and modified locomotives

Realize

Example:

Const Man = function () {this.run = function () {console.log ('running');}; const Decorator = function (old) {this.oldAbility = old.run; this.fly = function () {console.log ('capable of flying'); this.newAbility = function () {this.oldAbility (); this.fly ();}; const man = new Man () Const superMan = new Decorator (man); superMan.fly (); / / capable of flying

Agent mode

Define

The proxy pattern provides a proxy object to an object, and the proxy object controls the reference to the original object. Popularly speaking, the agency model is a common intermediary in our lives.

The implementation method defines a delegator and an agent, and the things that need to be delegated are done in the agent.

Usage scenarios in some cases, a client class does not want or cannot directly reference a delegate object, and the proxy class object can act as an intermediary between the client class and the delegate object. Agents can help clients filter out requests and defer creation of expensive objects until they are really needed. The agent buys the car, the purchasing agent and the class representative collects the homework for the teacher

Realize

Example:

Class Letter {constructor (name) {this.name = name;}} / / Dark lover Xiao Ming let XiaoMing = {name: 'Xiao Ming', sendLetter (target) {target.receiveLetter (this.name);},} / Agent Xiaohua let xiaoHua = {receiveLetter (customer) {/ / of course you have to wait for Xiao Hong to send love letters when she is in a good mood, and only when you send love letters do you create love letters XiaoHong.listenGoodMood (() = > {XiaoHong.receiveLetter (new Letter (love letters of customer +');});},} / / Xiao Hong let XiaoHong = {name: 'Xiao Hong', receiveLetter (letter) {console.log (this.name + 'received:' + letter.name);}, listenGoodMood (fn) {setTimeout (()) = > {fn ();}, 1000);},}; XiaoMing.sendLetter (xiaoHua); / / Xiao Hong receives a love letter from Xiao Ming

Proxy is an agent provided by ES6 that appears specifically in the proxy role. The responsive data part of Vue 3.0 deprecates Object.defineProperty and uses Proxy instead.

Var proxy = new Proxy (target, handler)

Now use Proxy to simulate another scenario: in order to protect the failing students, the class representative will only announce the passing grades after getting the class report card. Candidates who have doubts about the test scores have the right to update their scores only if the new score is 10 points higher than before after reconsideration.

Const scoreList = {wang: 90, li: 60, wu: 100}; const yyProxy = new Proxy (scoreList, {get: function (scoreList, name) {if (scoreList [name] > 69) {console.log ('output results'); return scoreList [name];} else {console.log ('failing grades cannot be made public') }, set: function (scoreList, name, val) {if (val-scoreList [name] > 10) {console.log ('modify grades'); scoreList [name] = val;} else {console.log ('cannot modify grades'); yyProxy ['wang'] = 98; / / unable to modify scores yyProxy [' li'] = 80 / / modify the results thank you for your reading, these are the contents of "what are the design patterns for Web development?" after the study of this article, I believe you have a deeper understanding of the design patterns that Web development should have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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