preface

Delivery Address:

Front end design pattern factory pattern

Proxy patterns for front-end design patterns

The strategy pattern of the front-end design pattern

Design mode chapter 4, to a decorative mode that is easily confused with the previous proxy mode (originally intended to write observer mode, here again real name diss someone’s buried point blog writing speed)

Decorator mode

What is decoration mode?

Definition of a Decorator pattern: a pattern that dynamically adds responsibilities (that is, additional functionality) to an object without changing its structure. It is an object structural pattern. A description of the GOF design pattern is quoted here.

The main advantages of the Decorator pattern are:

  • Extending the functionality of objects using decorator patterns is more flexible than using inheritance.
  • Different concrete decoration classes can be designed to create combinations of different behaviors.

The main drawback is that decorator mode adds many subclasses, which can be very complex if overused.

Distinction between decorator mode and proxy mode

First of all, they are complementary to methods, so there is some overlap in function, so there will be some confusion when looking at the proxy mode. Aren’t these two functions similar? Here is a simple distinction between the characteristics of both

The proxy mode focuses on the control of methods, while the adding behavior is passive for users.

Decoration mode mainly lies in the decoration method, increase the function of the method, add decoration for users is active.

In other words, when the proxy mode is used, the proxied object will not be modified, its function is single and known, and it has no sense of the proxy process. The proxied object neither knows what the proxy process does, nor will it change its own properties because of the proxy.

The decoration mode extends functions and attributes in the process of decorating the source object, and the attributes of the source object itself have been dynamically modified while being executed.

The biggest difference between the two is that the decoration mode is the developer’s initiative to modify the source object, while the proxy mode is the passive extension of the source object’s functionality.

Adornment pattern and proxy pattern are commonly understood

Okay, let’s get back to where we started — chestnut pet store

We mentioned in the agency model that we can choose the model of agency and franchise to expand our business. As agents, their choices can be diversified. In addition to our basic services, they will integrate their own business ideas and management concepts. In fact, we cannot impose high constraints on agents except the source of goods. In this case, agents may sell pets with some spicy chicken services (expired pet food, inferior pet cages, etc.) to affect our own brand effect.

Since this is the case, we can join the concept of direct-sale stores or take the initiative to provide expansion services when we provide basic services, so as to maintain the brand and influence of our pet stores.

The project of actual combat

The business sends ajax requests

const method = (type, url) = > {
    switch (type) {
        case 'GET': {
            return (target, name, descriptor) = > {
                return {
. descriptor, value(query) {  fetch.get({  url,  query  }).then(data= > {  descriptor.value.apply({ result: data }, [...arguments])  }).catch(err= > {  console.log('err====>', err)  })  }  }  }  }  default: {  return (target, name, descriptor) = > {  }  }  } }  class Business {  @method('GET'.'https://api.github.com/users/octocat')  getOct(params) {  console.log(params)  console.log('result==>'.this.result)  } }  const business = new Business()  business.getOct({  test: 1 }) Copy the code

If there are simple business requests in actual projects, it can be used in this way. The packaging of business requests is not the same as that introduced in the last chapter of FETCH practice project. In this way, the request is directly written in the business method, which has the advantage of simplicity and clarity. You can quickly see the request URL and mode of this business, but the disadvantage is that multiple nested requests are not easy to handle

Add the burial site

function consuming(target, name, descriptor) {
    return {
. descriptor,        value(query) {
            try {
 console.time('consuming')  console.log('Send buried point', query)  descriptor.value.apply(this, [...arguments])  } finally {  console.timeEnd('consuming')  }  }  } }  class Business {   @consuming  @method('GET'.'https://api.github.com/users/octocat')  getOct(params) {  console.log(params)  console.log('result==>'.this.result)  } }  Copy the code

The decorator mode is free to combine decorators, similar to the Onion mode, so we can add a buried point decorator to the method.

Function – anti – shake and throttling

As we all know, the anti-shake function is still a common requirement in daily development, so we can also add the anti-shake function to the decorator mode flexibly

function debounce(wait, immediate) { // The buffeting function can be delayed or executed immediately
    let timer;
    return (target, name, descriptor) = > {
        return {
. descriptor, value(query) {  if (timer) clearTimeout(timer);  if (immediate) {  letcallNow = ! timer; timer = setTimeout((a)= > {  timer = null;  }, wait);  if (callNow) descriptor.value.apply(this, [...arguments]);  } else {  timer = setTimeout((a)= > {  descriptor.value.apply(this, [...arguments])  }, wait)  }  }  }  } }  class Business {  @debounce(3000)  @consuming  @method('GET'.'https://api.github.com/users/octocat')  getOct(params) {  console.log(params)  console.log('result==>'.this.result)  } } Copy the code

Since anti-shake can, so throttle can

function throttle(wait) {
    let timeout;
    return (target, name, descriptor) => {
        return {
. descriptor, value(query) {  if(! timeout) { timeout = setTimeout(() => {  timeout = null;  descriptor.value.apply(this, [...arguments])  }, wait)  }  }  }  } } Copy the code

The above are examples of the use of decoration patterns in projects, partly for direct use, and partly for technical discussion.

The end of the

Complete demo address: project actual combat demo, like friends can star, the follow-up will be based on the launch of the design mode blog, and gradually expand the project.

Manual doghead town building


This article is formatted using MDNICE