Detailed explanation of js chain of responsibility model
The chain of responsibility pattern refers to a request that requires multiple objects to be processed, thereby avoiding the coupling relationship between the sender and receiver of the request. These objects are connected into a chain and the request is passed along the chain until an object handles it.
It can be found from examples in life that a certain request may require approval from several people. Even if the technical manager has completed the approval, it still needs approval from the next level. For example, if the leave is less than 3 days in the company, the direct leader can approve it. If it is between 3 and 7 days, it needs the approval of the project manager. If it is more than 7 days, it needs the approval of the technical director. Having introduced so many examples of the chain of responsibility pattern in life, the definition of the chain of responsibility pattern in object-oriented is given below.
The objects involved in the responsibility chain model only have the processor role, but since there are multiple processors, they have a common method of processing requests, so an abstract processor role is abstracted here for code reuse.
Implementation
-
Request class
// 采购请求 let PurchaseRequest = function (amount, productName) { this.amount = amount; this.productName = productName; };
Copy after login -
Handler interface Class
// 审批人,Handler let Approver = function (name, nextApprover) { this.name = name; this.nextApprover = nextApprover; }; Approver.prototype.processRequest = function () { throw new Error(); };
Copy after login -
Processor Class
// ConcreteHandler let Manager = function (name, nextApprover) { Approver.call(this, name, nextApprover); }; extend(Manager, Approver); Manager.prototype.processRequest = function (request) { if (request.Amount < 10000.0) { console.log('ok'); } else if (NextApprover != null) { this.nextApprover.ProcessRequest(request); } }; // ConcreteHandler,副总 let VicePresident = function (name, nextApprover) { Approver.call(this, name, nextApprover); }; extend(VicePresident, Approver); VicePresident.prototype.processRequest = function (request) { if (request.Amount < 25000.0) { console.log('ok'); } else if (NextApprover != null) { this.nextApprover.ProcessRequest(request); } }; // ConcreteHandler,总经理 let President = function (name, nextApprover) { Approver.call(this, name, nextApprover); }; extend(President, Approver); President.prototype.processRequest = function (request) { if (request.Amount < 100000.0) { console.log('ok'); } else if (NextApprover != null) { this.nextApprover.ProcessRequest(request); } };
Copy after login
Test
let requestTelphone = new PurchaseRequest(4000.0, "Telphone"); let requestSoftware = new PurchaseRequest(10000.0, "Visual Studio"); let requestComputers = new PurchaseRequest(40000.0, "Computers"); let manager = new Manager("LearningHard"); let Vp = new VicePresident("Tony"); let Pre = new President("BossTom"); // 设置责任链 manager.NextApprover = Vp; Vp.NextApprover = Pre; // 处理请求 manager.ProcessRequest(requestTelphone); manager.ProcessRequest(requestSoftware); manager.ProcessRequest(requestComputers);
Usage Scenario
When the approval of a system requires multiple objects to complete processing, such as a leave system, etc.
When there are multiple if-else statements in the code, you can consider using the chain of responsibility pattern to reconstruct the code.
Features
Reduces the coupling between the sender and receiver of the request.
Disperse multiple conditional judgments into various processing classes to make the code clearer and the responsibilities clearer.
The chain of responsibility model also has certain shortcomings, such as:
All conditional judgments must be executed before the correct processing object is found. Again, when the chain of responsibility is too long, it may cause performance problems, which may result in a certain request not being processed.
Summary
The chain of responsibility reduces the coupling between the requester and the receiver, allowing multiple objects to have the opportunity to process a request . Makes the division of responsibilities more specific, helping to expand
Related recommendations:
Introduction to JavaScript responsibility chain model
Instance analysis of the chain of responsibility pattern in Java design patterns
The chain of responsibility pattern of commonly used design patterns and its PHP implementation
The above is the detailed content of Detailed explanation of js chain of responsibility model. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a
