[encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern

woow_ wu7 2021-05-03 14:44:45
encapsulation design pattern command pattern


Navigation

[react] Hooks

[ encapsulation 01- Design patterns ] Design principles and Factory mode ( Simple abstract method ) Adapter pattern Decorator mode
[ encapsulation 02- Design patterns ] Command mode The flyweight pattern Portfolio model The proxy pattern

[React Practice from scratch 01- backstage ] The code segment
[React Practice from scratch 02- backstage ] Access control
[React Practice from scratch 03- backstage ] Customize hooks
[React Practice from scratch 04- backstage ] docker-compose Deploy react+egg+nginx+mysql
[React Practice from scratch 05- backstage ] Gitlab-CI Use Docker Automated Deployment

[ Source code -webpack01- Pre knowledge ] AST Abstract syntax tree
[ Source code -webpack02- Pre knowledge ] Tapable
[ Source code -webpack03] Handwriting webpack - compiler Simple compilation process
[ Source code ] Redux React-Redux01
[ Source code ] axios
[ Source code ] vuex
[ Source code -vue01] data Response type and Initialize rendering
[ Source code -vue02] computed Response type - initialization , visit , The update process
[ Source code -vue03] watch Listening properties - Initialization and update
[ Source code -vue04] Vue.set and vm.$set
[ Source code -vue05] Vue.extend

[ Source code -vue06] Vue.nextTick and vm.$nextTick
[ Deploy 01] Nginx
[ Deploy 02] Docker Deploy vue project
[ Deploy 03] gitlab-CI

[ Data structures and algorithms 01] Binary search and sort

[ thorough 01] Execution context
[ thorough 02] Prototype chain
[ thorough 03] Inherit
[ thorough 04] The event loop
[ thorough 05] currying Partial function Function memory
[ thorough 06] Implicit conversion and Operator
[ thorough 07] Browser caching mechanism (http Caching mechanisms )
[ thorough 08] Front end security
[ thorough 09] Depth copy
[ thorough 10] Debounce Throttle
[ thorough 11] Front-end routing
[ thorough 12] Front-end modularization
[ thorough 13] Observer mode Publish subscribe mode Two way data binding
[ thorough 14] canvas
[ thorough 15] webSocket
[ thorough 16] webpack
[ thorough 17] http and https
[ thorough 18] CSS-interview
[ thorough 19] Handwriting Promise
[ thorough 20] Handwritten functions
[ thorough 21] Data structures and algorithms - Binary search and sort
[ thorough 22] js and v8 Garbage collection mechanism
[ thorough 23] JS Design patterns - agent , Strategy , Single case

[ Front end learning java01-SpringBoot actual combat ] Environment configuration and HelloWorld service
[ Front end learning java02-SpringBoot actual combat ] mybatis + mysql Add, delete, modify and search songs
[ Front end learning java03-SpringBoot actual combat ] lombok, journal , Deploy
[ Front end learning java04-SpringBoot actual combat ] Static resources + Interceptor + Front and back end file upload
[ Front end learning java05-SpringBoot actual combat ] Commonly used annotations + redis Realize the statistical function
[ Front end learning java06-SpringBoot actual combat ] Inject + Swagger2 3.0 + unit testing JUnit5
[ Front end learning java07-SpringBoot actual combat ] IOC Scanner + Business + Jackson

( One ) Pre knowledge

(1) Pre knowledge

scaffolding The scaffold
cluster colony
handler Handle
Typography Typesetting
invoke call
maintainer Maintainer
fly The fly
flyweight The flyweight pattern
recover Recycling
pattern Pattern
design pattern Design patterns
strategy The strategy pattern
singleton Single column mode
expires Be overdue
 Copy code 

(2)layout

xs => extra small Supersmall
sm => small
md => medium medium Medium
lg => large
xl => extra large Super large
 Copy code 

(3) pro-table

Protable => search={false} Custom find
 Copy code 

(4) The local branch is associated with the remote branch

git branch --set-upstream-to=origin/remote_branch your_branch
 Copy code 

( Two ) Command mode

  • Command mode is a highly cohesive mode
  • Concept
    • Encapsulate a request as an object , So that you can use ( Different requests parameterize the client ),( Queue requests or log them ), It can provide the undo or resume function of the command
    • The core of the command mode is the introduction of ( Command class )
  • role
    • caller / Publisher invoker => command , Call command object , Yes reciver invisible , Don't know who and how to execute
    • The receiver / practitioners receiver => Carry out orders , Provide the corresponding interface to process the request
    • Command object command => Command object , call ( Interface corresponding to the receiver ) To deal with it ( The publisher's request )
  • characteristic
    • invoker and reciver Are independent of each other , Encapsulate the request as command, The specific execution of the request is ( command Object call reciver Provides an interface to perform )
    • ( Command object command ) Namely ( caller invoker ) and ( The receiver reciver ) The bridge , Decoupling callers and receivers
// Command mode
// Invoker Publisher
// 1. Among the publishers are Command object
// 2. The publisher issues commands , Call the method in the command object , The command object calls the receiver's method
class Invoker {
constructor(command) {
this.command = command
}
invoke = () => {
this.command.execute()
}
}
// Command Command object
// 1. The command object has The receiver
// 2. Command object Call the method in the receiver
class Command {
constructor(receiver) {
this.receiver = receiver
}
execute() {
this.receiver.execute()
}
}
// Receiver The receiver
// The receiver Execute the final request
class Receiver {
execute() {
console.log(' Receiver execution method ')
}
}
const cook = new Receiver() // The cook - The receiver - Cooking
const shop = new Command(cook) // The store - Command object - Order the cook to cook
const user = new Invoker(shop) // Customer - caller - command
user.invoke()
 Copy code 

( 3、 ... and ) The flyweight pattern flyweight pattern

  • Use sharing technology to reduce the number of objects created , This reduces memory usage , Improve performance
  • ( The flyweight pattern ) Remind us of , Will a ( Object properties ) Divided into ( Internal state ) and ( External state )
    • Internal state : Shared by a collection of objects , Usually it doesn't change
    • External state : Change frequently according to the application scenario
  • The sharing mode is ( Trade time for space )
  • Application scenarios
    • As long as it takes a lot of creation ( Duplicate class code ), You can use the Heyuan mode to pull out ( Internal state and external state ), So as to reduce the creation of duplicate classes
  • Related words
    • flyweight
    • fly It means fly
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="radio" value="red" name="color" checked> Red
<input type="radio" value="yellow" name="color"> yellow
<input type="radio" value="blue" name="color"> Blue
<button onclick={draw()}> draw </button>
<div id="container"> Color </div>
<script>
// The flyweight pattern
class FlyweightDiv {
constructor() {
this.element = document.createElement('div') // ----- Internal attributes , unchanged
}
setColor = (color) => { // ---------------------------- Outside, outside , change
this.element.style=`width: 100px; height: 100px; background-color:${color}`
}
}
const myDiv = new FlyweightDiv()
const draw = () => {
const btns = Array.from(document.getElementsByName('color'))
const checkedBtn = btns.find(btn => btn.checked)
const color = checkedBtn?checkedBtn.value:'red'
console.log(`color`, color)
myDiv.setColor(color)
document.getElementById('container').appendChild(myDiv.element)
// Be careful : It's the same one here every time element, So we don't add new
}
</script>
</body>
</html>
 Copy code 

( Four ) Portfolio model compose pattern

  • take ( Objects are combined into a tree structure ), To indicate that ( part - whole ) Hierarchical structure
  • Customers can use a unified approach , treat ( Combine objects ) and ( Leaf object )
  • Also known as the whole - Partial mode
  • key word
    • part / whole
    • Leaf object / Combine objects
  • characteristic
    • Leaf like structure , Is part of / The overall hierarchy
    • Consistent operability ,( Tree objects and leaf objects ) Keep the external interface consistent , namely ( The operation is consistent with the data structure )
    • Top down requests are popular , from ( The tree object is passed to the leaf object )
    • Call the top level object , It will traverse the leaf object under it and execute

image.png

image.png

 Implement a tree file structure
- folder Folder
- file file
- Files can be created under the folder , Files can no longer be created
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// Portfolio model
// 1. Floder Tree object
// 2. File Leaf objects
// 3. Folder and File Unified interface , All have add and scan Method
class Floder {
constructor(name) {
this.name = name;
this.files = [];
}
add = (file) => {
this.files.push(file);
};
scan = () => {
this.files.forEach((file) => file.scan());
};
}
class File {
constructor(name) {
this.name = name
}
add = () => {
throw new Error(' File cannot be added below , You can add files under the folder ')
}
scan = () => {
console.log(` Scanning files : ${this.name}`)
}
}
const carFolder = new Floder(' vehicle ')
const bmwFile = new File(' BMW ')
carFolder.add(bmwFile)
carFolder.scan()
</script>
</body>
</html>
 Copy code 

( 5、 ... and ) review - The proxy pattern proxy pattern

  • Definition
    • to ( An object ) Provide a ( Proxy object ), And by the ( Proxy object ) To control ( Reference to the original object ), Proxy objects are similar to ( The mediation )
  • role
    • Customers
    • Proxy object
    • Delegate object
    • ( Customers ) === ( Proxy object ) === ( Delegate object )
  • characteristic
    • ( Proxy object ) It doesn't provide services , But by calling ( Delegate object ) To provide specific services , namely ( The real business function is still the delegate object ) To achieve
    • ( Proxy object ) It is mainly responsible for ( Preprocessing messages , Filtering messages , Forward a message )
    • ( proxy class ) Apart from ( Customer class ) and ( Delegation class ) Out of the agency of , You can also add additional functions to the proxy class to extend the functions of the delegate class , In this way, we can directly modify the proxy class instead of the delegate class , Comply with the opening and closing principle of code design

actual combat

(5-1) The proxy pattern - ajax Request to add cache function

  • principle
    • ( cache ) Every time you request ( Parameters ) and ( Return value ), If the parameters are the same , Go straight back ( map ) The return value corresponding to the parameter in
    • utilize ( The proxy pattern ) Add new logic to the original function without affecting the original function , Equivalent to using ( Function combination ) To achieve ( Reuse logic and add logic )
    • Remember to compare my previous articles
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// The proxy pattern
// A normal request
const request = (params) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve(`data: ${params}`);
}, 1000);
});
};
// The proxy pattern - Agent request
const proxyRequest = (params) => {
return cache(params);
};
// map Used to map parameters and return values
const mapInstance = new Map();
// utilize map Cache parameters and return values
const cache = async (params) => {
// Parameter in map in , Directly return the request result corresponding to the parameter
if (mapInstance.has(params)) {
return mapInstance.get(params);
}
// Parameter in map Does not exist in the , Then request and do the mapping of parameters and request return values
// therefore : When the parameter exists , Directly from map Back in , Instead of asking again
console.log(" In this case , I only do it once ");
const res = await request(params);
mapInstance.set(params, res);
return res;
};
proxyRequest(" Parameters ").then((res) => console.log(`res`, res));
setTimeout(() => {
proxyRequest(" Parameters ").then((res) => console.log(`res`, res));
}, 2000);
</script>
</body>
</html>
 Copy code 

image.png

(5-2) The proxy pattern - Proxy cache , Processing cache expiration time

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
class Storage {
constructor(type, expires) {
this.storage = window[type];
this.expires = expires;
}
// save
// Acting as a native setItem() Method , Add cache expiration time
setItem = (key, value) => {
this.storage.setItem(
key,
JSON.stringify({
value,
setTime: +new Date(), // --------------------- ( save ) The timestamp
})
);
};
// take
// Acting as a native getItem() Method , According to the incoming expiration time , To determine whether the data is out of date
getItem = (key) => {
const now = +new Date(); // --------------------- ( take ) The timestamp
const { value, setTime } = JSON.parse(this.storage.getItem(key));
if (now - setTime > this.expires) {
this.storage.removeItem(key); // -------------- Expired delete
}
return this.storage.getItem(key);
};
}
const localStorageInstance = new Storage("localStorage", 5000);
localStorageInstance.setItem("name", "woow_wu7");
console.log(" Not expired ", localStorageInstance.getItem("name"));
setTimeout(() => {
console.log(" Be overdue ", localStorageInstance.getItem("name"));
}, 6000);
</script>
</body>
</html>
 Copy code 

image.png

( 6、 ... and ) review - The strategy pattern

  • Concept
    • Define a series of algorithms , Seal them up one by one , And enable them to ( Replace each other )
    • take ( The unchanging part ) and ( The Ministry of change ) Separate , It's kind of like ( The flyweight pattern )
    • ( The strategy pattern ) The main purpose of ( The use of algorithms ) and ( Implementation of algorithm ) Separate from
  • member
    • ( The strategy pattern ) It mainly includes ( Policy class ) and ( The environment class )
    • Policy class
      • It encapsulates the specific algorithm , And responsible for the specific calculation process
    • The environment class
      • ( The environment class ) context be responsible for ( Accept the customer's request ), Then put the ( The request is delegated to a policy class )
  • advantage
    • Avoid multiple choice statements : The strategy model uses ( Combine entrust polymorphic ) And so on , Can effectively avoid ( Multiple conditional choice statements , such as if...else perhaps switch Appearance )
    • In line with the open and closed design principles : It can be extended and not modified , Encapsulate the algorithm in a separate strategy Strategy , Make it easy for them to switch , understand , Expand
    • Computing and sending can be reused : It can be taken elsewhere in the system , So as to avoid redundant and repetitive work
  • shortcoming
    • You have to understand all the strategies , It's important to understand the differences between the strategies , To achieve a characteristic strategy

(6-1) Calculate the bonus

  • The rules
    • S The performance of - 4 Double salary
    • A The performance of - 3 Double salary
    • B The performance of - 2 Double salary
  • Some words
    • bonus Bonus
    • salary Wages
    • performance The performance of performance
    • strategy pattern The strategy pattern
(1) Write without any optimization
- shortcoming
- There's a lot of if...else
- Lack of scalability : If you want to add C The performance of , You have to modify the internal function implementation , Violation of the open and closed principle can be extended, but ( Do not modify the )
- Poor reusability
- bonus Bonus
- performance The performance of
- salary Wages
const getBonus = (performance, salary) => {
if (performance === 'S') return 4 * salary;
if (performance === 'A') return 3 * salary;
if (performance === 'B') return 2 * salary;
}
getBonus('A', 1000) // Output 3000
-------
(2) Use The strategy pattern strategy pattern Refactoring code
- advantage
- Avoid multiple if...esle
- Conform to the open policy / Closed principle , Extension doesn't need to modify the original logic , It doesn't affect the original logic
- All calculated bonuses bonus The logic is not in getBonus Functions are environment classes context in , It's distributed across policy objects strategyPattern in
- context The environment class is not responsible for computing , Just responsible for delegating requests to strategyPattern Policy class
const strategyPattern = {
S: (salary) => 4 * salary,
A: (salary) => 3 * salary,
B: (salary) => 1 * salary,
}
const getBonus = (performance, salary) => strategyPattern[performance](salary)
getBonus('A', 1000) // Output 3000
 Copy code 

Information

Command mode ( Streamlining ) juejin.cn/post/684490…
The flyweight pattern techblog.sishuxuefu.com/atricle.htm…
The flyweight pattern juejin.cn/post/684490…
Portfolio model juejin.cn/post/684490…
The proxy pattern [ My Nuggets ] juejin.cn/post/691874…

版权声明
本文为[woow_ wu7]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503144051129V.html

  1. Why did gitlab choose vue.js?
  2. HTTP-RPC: 轻量跨平台REST服务
  3. 继全面采用Node.js以后,PayPal分享大幅度踩坑GraphQL心得 - Mark Stuart
  4. vue组件化开发实战之滚动/轮播的实现
  5. Http-rpc: lightweight cross platform rest Service
  6. Following the full adoption of node.js, PayPal shares a great deal of graphql experience mark Stuart
  7. Implementation of rolling / carousel in Vue component development
  8. CSS是什么?这一篇全解,绝对有你想要的
  9. What is CSS? This is a complete solution, there is absolutely what you want
  10. 04-HTML5常用标签-HTML5极速入门
  11. 04-html5 common tags
  12. WEB前端全套零基础视频教程+软件2021最新编程视频
  13. Web front end full set of zero basic video tutorial + software 2021 latest programming video
  14. 使用Node, Mongo, React, Redux实现Token认证
  15. Using node, Mongo, react and Redux to realize token authentication
  16. 体面编码之CSS和HTML
  17. CSS and HTML for decent coding
  18. 使用Playwright基于多浏览器进行javascript自动化测试的简单教程- Applitools
  19. A simple tutorial for JavaScript automatic testing based on multi browser using playwright - applitools
  20. Minimum distance to target element
  21. 浅谈 React 中的 XSS 攻击
  22. XSS attack in react
  23. 自学前端教程整理,附不容错过的前端100篇文章合集
  24. Self taught front-end tutorial collation, with a collection of 100 front-end articles that can not be missed
  25. 使用OpenTracing跟踪Go中的HTTP请求延迟
  26. Using opentracing to track HTTP request latency in go
  27. Encapsulating databinding allows you to write less than 10000 lines of code
  28. 03-HTML5标签-HTML5极速入门
  29. 03-html5 tag-html5 quick start
  30. LayUI - 极易上手拿来即用的前端 UI 框架
  31. Layui - easy to use front end UI framework
  32. Interpretation of lodash source code (1)
  33. Why is the first parameter of node family callback error?
  34. 报告:JavaScript 开发者达1380 万,C#超越 PHP,Rust 增长最快
  35. Report: Javascript developers reach 13.8 million, C surpasses PHP, and rust grows fastest
  36. 小白前端入门笔记(10),怎么设置网站内部的超链接?
  37. How to set up hyperlinks inside the website?
  38. Using node and socket to realize online chat room
  39. The core competitiveness of Vue: data bidirectional binding
  40. React configuration agent
  41. CSS layout
  42. Application scenario explanation of Vue dynamic component
  43. Redux learning notes 04 -- using multiple reducers to manage data
  44. After three months of typescript writing, what have I learned?
  45. Node family - what is a callback?
  46. React -- a simple implementation of render & create element
  47. JS learning simple usage of jquery
  48. Seamless love
  49. 小白前端入门笔记(12),设置哑链接
  50. Small white front-end entry notes (12), set dumb links
  51. Vue2. X opens composition API and TSX
  52. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  53. Flex learning notes
  54. The most essential closure article in the eastern hemisphere
  55. 2021-05-03 hot news
  56. Sword finger offer -- reverse order pair in array (JS Implementation)
  57. Working process of scaffold
  58. Use decorator mode to strengthen your fetch
  59. [JS] scope (Introduction)
  60. Employment information statistics network (interface document)