navigation

[react] Hooks

[Encapsulation – Design Patterns 01] Design principles and factory patterns (simple abstract methods) Adapter patterns decorator patterns

[React from zero practice 01- background] code split [React from zero practice 02- background] permission control [React from zero practice 03- background] custom hooks [React from zero practice 04- background] docker-compose Deploy React + Egg +nginx+mysql [React From zero practice 05- background] Gitlab-CI using Docker automated deployment

[source code – Webpack01 – precompiler] AST abstract syntax tree [source code – Webpack02 – Precompiler] Tapable [source code – Webpack03] hand written webpack-compiler simple compilation process [source code] Redux React-redux01 [source] Axios [source] vuex [source -vue01] Data reactive and initialize render [source -vue02] Computed responsive – Initialize, access, Update Procedure [source -vue04] Watch Listening properties – Initialize and update [source -vue04] vue. set and vm.$set [source -vue05] vue.extend

[source -vue06] Vue. NextTick and VM.$nextTick [Deployment 01] Nginx [Deployment 02] Docker deployVUE project [Deployment 03] Gitlab-CI

[Data Structures and Algorithms 01] Binary search and sort

[Deep 01] Execution context [Deep 02] Prototype chain [Deep 03] Inheritance [Deep 04] Event loop [Deep 05] Curri Bias function [Deep 06] Function memory [Deep 07] Implicit conversions and operators [Deep 07] Browser caching mechanism (HTTP caching mechanism) [Deep 08] Front-end security [Deep 09] Deep copy [Deep 10] Debounce Throttle [Deep 10] Front-end routing [Deep 12] Front-end modularization [Deep 13] Observer mode Publish subscribe mode Bidirectional data binding [Deep 14] Canvas [Deep 15] webSocket Webpack HTTP and HTTPS CSS- Interview Handwriting Promise Data Structures and Algorithms – Binary Search and Sorting Js Design Patterns – Agents, policies, singletons

/ front-end learn java01 – SpringBoot combat environment configuration and the HelloWorld service [front-end learn java02 – SpringBoot combat] mybatis + mysql implementation song to add and delete [front-end learn java03 – SpringBoot combat] Lombok, log, Java04 -SpringBoot combat deployment [front-end science Java04 -SpringBoot combat] static resources + interceptor + front and back end file upload [front-end science Java05 -SpringBoot combat] common annotates + Redis implementation statistics function [front-end science Java06 -SpringBoot combat] inject Swagger2 3.0 + unit test JUnit5 IOC scanner + transaction + Jackson

(1) Pre-knowledge

(1) Some words

Principle diction in chinese-English translation // Substitution principle // Substitution principle A. show up B. show up // Advanced configuration Constraint peek peek shape anonymousCopy the code

(2) Error

  • new Error(message)
  • When an Error instance object is thrown, the entire program stops executing at the point where the Error occurred
  • Error instance attribute
    • Message Indicates an error message
    • Name Error name (non-standard attribute)
    • Stack Error stack (nonstandard attribute)
  • Six error objects
    • SyntaxError SyntaxError
    • ReferenceError (an error that occurs when referring to a non-existent variable) or (assigning a value to an object that cannot be allocated)
    • RangeError Error that occurs when a value is out of the valid range
    • An error that occurs when TypeError (a variable or parameter) is not of the expected type
    • RUIError An error that is thrown when the parameters of the URI-related function are incorrect
    • EvalError An error that is thrown when the eval function is not executed correctly
  • The seventh is a custom error object
    • The principle of
      • 1. Is a normal constructor (name, message, stack, etc.)
      • 2. Point the constructor’s prototype property to the instance generated by new Error()
      • 3. Point the constructor’s prototype.contructor property to the constructor itself to prevent reference errors
  • Throw statement
    • The throw statement is used to manually interrupt program execution and throw an error
    • Note: A throw can throw a value of any type, not necessarily an instance of an error
    Try {/ / throw new Error (' mistake ') / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- note: } catch(e) {// console.log(e.message) ----- Note: Is corresponding to the try to throw the error object, false object with the message attributes / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- note: catch () of the value of the parameter is thrown in the try block, which also can be any type of console. The log (e); }Copy the code
  • try... The catch (e) structure
    • try… Catch is used to handle errors and choose whether to proceed
    • The argument that catch(e) accepts represents the value thrown by the try block, of any type, because a throw can throw any type
    • Note: After catching an error, the program does not interrupt and will continue executing as normal
    Try {throw "something went wrong "; } catch (e) { console.log(111); } console.log(222); // 111 // 222 will still execute normallyCopy the code
    • try… Catch can also be nested with a try… catch
  • try... Finally the structure
    • try… The catch structure allows a finally block to be added at the end, representing the statement that must be run last whether or not an error occurs
    • If in the try... If a catch has a return statement, it will execute the statement following the return only after the finally execution has completed

(ii) Six design principles

  • The Single Responsibility Principle
  • Open Closed Principle
  • The Liskov Substitution Principle
  • The Law of Demeter
  • Interface Segregation Principle
  • Dependence Inversion Principle

(2.1) Single responsibility principle

  • keywords
    • (Single) (Duty)
    • If we have two motivations to rewrite a method, then the method has two responsibilities
  • Single responsibility principle
    • A method only does one thing
    • In this way, only the least granular methods will be affected by requirements changes, and the rest will not be affected
  • How are responsibilities divided??
    • Two completely different functions should not be placed in one class
    • A class should be (a set of highly correlated functions, or encapsulation of data)
    • If two responsibilities always change at the same time as requirements change, there is no need to separate them
    • Even if the two responsibilities have been coupled together and there are no signs of them changing, it may not be necessary to actively separate them
  • Advantages and disadvantages of the single responsibility principle
    • advantages
      • Reduced the size of a single class or object
      • Splitting classes and objects into (smaller granularity) by (responsibility) facilitates (code reuse) (unit testing), etc
      • When one responsibility changes, it does not affect other responsibilities
    • disadvantages
      • Increased code complexity
      • Makes it harder for objects to relate to each other

(2.2) Open and closed principle

  • keywords
    • Open – close principle: classes, objects, modules, functions are (extensible), but (unmodifiable)
    • That is, when you need to add functionality or modify functionality to a program, you can try to add code, but you can’t modify the source code
  • case
    • Eliminate (conditional branching) with (polymorphism) of objects
    • By separating (stable parts) from (easily changing parts), only the parts that change frequently need to be modified during the evolution of the system iteration, and the parts that change use (hook functions) and (callback functions).
  • advantages
    • The original code is unchanged
    • You can reuse the original unmodified code
  • Summary of the principle of openness and closure
    • Both concrete design patterns and more abstract object-oriented design principles, such as the single responsibility principle, the least knowledge principle, and the dependency inversion principle, have emerged to make programs conform to the open-close principle

(2.3) Minimum knowledge principle

  • concept
    • A (Objects, classes, modules, functions, variables) should have minimal knowledge of other objects,Reduce the coupling between objects

(2.4) Richter substitution principle

  • concept
    • All references to (base class) must be able to be replaced directly with (subclass)
  • The characteristics of
    • A subclass must implement all methods of its parent class, i.e. inherit all methods and properties of its parent class
    • Subclasses can have their own properties and methods (override or add new properties)
    • When overwriting or implementing methods of the parent class, the input arguments can be magnified and the output narrowed

(2.5) The principle of dependence inversion

  • Inter-module dependencies occur through abstractions (such as interfaces) and do not directly depend on implementation classes (which can implement methods in interfaces)
  • (interface or abstract class) does not depend on (implementation class)
  • (implementation class) depends on (interface or abstract class)

(2.6) Interface isolation principle

  • A client should not rely on interfaces it does not need
  • Establish a single interface

(3) Factory mode

(3.1) Simple factory mode

  • In the simple factory model, it is the factory that creates the product, the boss and the attendant
Constructor (public name: constructor) {constructor(public name: constructor); String) {// this.name = name}} Class Cat extends Animal {} class Dog extends Animal { Class AnimalFactory {static create(name: name); class AnimalFactory {static create(name: name); String) {// switch (name) {// create a case 'cat' by calling a constructor based on the type passed in: return new Cat('cat') case 'dog': return new Dog('dog') default: Return new Error(' Error ')}}} const dog = animalfactory.create ('dog') Log (dog) console.log(cat)Copy the code

(3.2) Factory method pattern

  • In the simple factory model, it is the factory that creates the product, the boss and the attendant
  • In the factory method pattern, instead of the factory creating the product, the specific factory is created first, and then the specific factory creates the product
  • Instead of being done by your boss, you have to give orders to someone else to do it
  • That is, factories order other factories to produce products
The abstract class Animal {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - product / / abstract class method does not need to own constructor (public name: String) {/ / this. Name = name}} class Cat extends Animal {} / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Cat class specific products Dog extends Animal {} / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- specific products Dog the abstract class AnimalFactory {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- specific types of abstract class factory the abstract createAnimal () : Animal} class CatFactory extends AnimalFactory {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- to create the cat factory, CreateAnimal () {return new Cat(' Cat ')}} Class DogFactory extends AnimalFactory {// ------------------------ create dog's factory, CreateAnimal () {return new Dog(' Dog ')}} class Factory {// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the factory class / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Static create(name: name) static create(name: name) String) {// switch (name) {// create a case 'cat' by calling a constructor based on the type passed in: return new CatFactory().createAnimal() case 'dog': return new DogFactory().createAnimal() default: Const cat = factory.create ('cat') console.log('cat') console.log(cat)Copy the code

(3.3) Abstract factory pattern

Abstract class Cat {} Abstract class Dog {} Class ChinessCat extends Cat {} class ChinessDog extends Dog {} // China Dog class EnglishCat extends the Cat {} / / the Cat class EnglishDog extends Dog {} / / the Dog the abstract class AnimalFactory {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - an abstract factory class = > abstract abstract factory createCat () : the Cat the abstract createDog () : Dog} class ChineseAnimalFactory extends AnimalFactory {// ----------- => createCat() {return new ChinessCat() } createDog() { return new ChinessDog() } } class EnglishAnimalFactory extends AnimalFactory { // ----------- createCat() {return new EnglishCat()} createDog() {return new EnglishDog()}} const ChineseAnimal = new ChineseAnimalFactory() // ------------- chineseAnimal const chineseCat = chineseanimal.createcat () // ----------------- chineseCat console.log(chineseCat)Copy the code

(4) Adapter mode

  • The adapter pattern, also known as the wrapper pattern, converts the interface of a class into another interface that the user needs to solve the problem of interface incompatibility between classes or objects
  • The old interface is not compatible with the user
  • An adapter conversion interface is added in the middle
Class Rmb {output() {return '100rmb'}} abstract class Money {abstract transform(): String} class MoneyAdaptor extends Money {// constructor(RMB: RMB) {super() this.rmb = Rmb} transform() {return this.rmb. Output () + 'convert'}} const dollar = new MoneyAdaptor(new) Rmb()) console.log(dollar.transform());Copy the code

(4.1) What are the applications of the adapter mode

  • The Adaptor function in Axios that distinguishes the browser from the node
  • Attribute of computed in VUE

(4.2) Adaptor Pattern Application Case – AXIos

  • Adapter functions in AXIos call different request methods depending on the system type, such as XMLHttpRequest in the browser and HTTP modules in the Node environment, smoothing the difference
  • Adapter in axios source code
1. var adapter = config.adapter || defaults.adapter; Var defaults = {var defaults = {var default = {var default = {var default = {var default = {var default = {var default = {var default =}} getDefaultAdapter() } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest ! == 'undefined') { adapter = require('./adapters/xhr'); } else if (typeof process! == 'undefined' && Object.prototype.toString.call(process) === '[object process]') { adapter = require('./adapters/http'); // Node environment} return adapter; }Copy the code
  • Write an Adapter function in AXIOS
axios({ method: "GET", url: "www.baidu.com", }).then( (value) => console.log(value), (reason) => console.error(reason) ); // The design pattern yuanze // 1. => a function implements only one logic // 2. 3. Minimum knowledge => Modules, functions, methods, and variables should rely on other classes and objects as much as possible // 4. < span style = "color: RGB (99, 99, 99); color: RGB (99, 99, 99); Function xhrAdaptor(config) {const {method, url} = config; function xhrAdaptor(config) {const {method, url} = config; return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open(method, url, true); xhr.setRequestHeader("Content-Type", "application/json"); Xhr. responseType = "json"; // setRequestHeader must be open before send; xhr.onreadystatechange = function () { if (xhr.readyState ! == 4) { return; / / readyState / / 0 UNSENT -- -- -- -- -- -- -- -- -- -- -- -- -- XHR instance has been created, the open () method has not been OPEND call / / 1 -- -- -- -- -- -- -- -- -- -- -- -- -- -- the open () method is called, the send () method is invoked, // 2 HEADERS_RECEIVED -- send() method is called, // 3 LOADING ------------ Response Entity body is being downloaded. Response may already have response data // 4 DONE --------------- The whole data transmission process has been completed, Return resolve(xhr.responseText);} if (xhr.status === 200) {// readyState === 4 && status === 200 return resolve(xhr.responseText); } else { return reject(new Error(xhr.statusText)); }}; xhr.onerror = function () { console.error("error"); }; // xhr.onload = function() { // if (xhr.status > 200 && xhr.status < 300 || xhr.status === 304) { // return resolve(xhr.responseText) // } // } xhr.send(); }); Function httpAdaptor(config) {const {method, url} = config const HTTP = requrie(' HTTP ') const {hostname, Port, path} = url.parse(URL) return new Promise((resolve, reject) => {// HTTP module const options = {method, hostname, port, path }; let req = http.request(options, function (response) { let chunks = []; response.on("data", function (chunk) { chunks.push(chunk); }); response.on("end", function () { const result = Buffer.concat(chunks).toString(); return resolve(result); }); }); req.on("error", function (error) { return reject(error); }); }); } function getDefaultAdaptor () {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- adapter pattern, according to the different methods of environmental call let adaptor. if (typeof XMLHttpRequest ! == "undefined") {// ------ browser environment adaptor = xhrAdaptor; } if (typeof process ! = = "undefined") {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- the node environment adaptor = httpAdaptor; } return adaptor; } function axios(config) { const adaptor = getDefaultAdaptor(); return adaptor(config); // The axios return value is a promise object, either on the browser side or on the node side}Copy the code

(5) Decorator mode

  • The decorator pattern is a way to add more functionality to an existing function. It is a structural design pattern that extends an existing class
  • Is a design pattern that relies on (composition) to implement (function extension of classes) and supports (multi-level nesting)
  • Adding logic directly would violate both the single responsibility principle and the Open closed principle
  • Common decorators are class decorators property decorators method decorators parameter decorators
Abstract class Shape {// abstract draw(): void; } class Circle extends Shape {// draw() {console.log(" draw Circle "); }} class Rectagle extends Shape {// draw() {console.log(" Draw rectangle "); }} this class extends Shape () {// constructor() {super(); } abstract draw(): void; } class Red extends Color { draw() { this.shape.draw(); New Circle() console.log(" draw Red "); // Call the draw method on the passed argument instance, passing new Circle() console.log(" draw Red "); } } class Yellow extends Color { draw() { this.shape.draw(); Console. log(" Draw yellow "); } } const redCircle = new Red(new Circle()); Redcircle.draw () // Calls the draw method on the instanceCopy the code

data

Design Principles 1 juejin.cn/post/684490… Design Principles 2 juejin.cn/post/684790… Decorator mode 1 juejin.cn/post/691423… Decorator Mode 2 juejin.cn/post/688189…

Vscode =>codeRunner=> Garbled characters occur on ts-Node. The solution is as follows: github.com/formulahend…