preface

The application of Design Pattern in VUE (1) The application of design pattern in VUE (2) the application of design pattern in VUE (3) the application of design pattern in VUE (4) The application of design pattern in VUE (5) the application of design pattern in VUE (6) The application of design pattern in VUE (7)

Why write these articles. Just as Design Pattern is a set of repeatedly used, known by most people, classified and summarized code Design experience (from Baidu Encyclopedia), I also want to discuss the charm of Design Pattern with everyone through sharing some accumulated work. The application scenarios introduced in this series of articles as an aid to illustration are real application scenarios in the workplace, of course, but common business scenarios are also covered by analogy



First, the adapter pattern

Adapter is equivalent to the existence of the peacemaker, the adapter in life common scenarios:

  • Switch from two sockets to three
  • Android charging cable interface to iPhone

From the above two examples, it should be easy to see that the adapter is used in incompatible scenarios, which are represented in the code as multiple objects, each of which performs a different method. In this case, the adapter should be used to define the method to be called.

The adapter pattern (sometimes called wrapper style or wrapper) ADAPTS the interface of a class to what the user expects. An adaptation allows classes that would normally not work together because of interface incompatibilities to work together by wrapping the class’s own interface in an existing class

scenario

Suppose we used Swiper in our project as follows:

<swiper :prop-x="px" :prop-y="py" :prop-z="pz" />
Copy the code

Then came a more powerful and better sliding component called NbSwiper, which works as follows:

<nb-swiper :prop-x="px" :prop-yy="pz" :prop-z="pw" />
Copy the code

The comparison shows that

Swiper NbSwiper The component data
prop-x prop-x px
prop-y There is no py
prop-z prop-yy pz
There is no prop-z pw

Now the requirement is to replace all Swiper components in the project with NbSwiper as shown in the table above:

The two components handle 'prop-x' in the same way, and the other properties' prop-Y ', 'prop-YY', and 'prop-Z' have certain differences. It's a bit more work to make changes one by one in the code, and it's hard to handle compatibility issues without bugsCopy the code
Adapter mode play

To solve this problem, we can choose Swiper as a decorative component

// Swiper. Vue // The Swiper component used in the project will be replaced. We will wrap a Swiper component <template> <! <nb-swiper :prop-x="propX" :prop-yy="propZ" :prop-z="propW" />
</tempalte>
<script>
  exportDefault {props: {// Props: String, propY: String, propYy: String, propZ: String, propW: String, } ... } </script>Copy the code

Now all we need to do is add compatibility to NbSwiper’s new property values in our code

Second, decorator mode

Definition (from Baidu Baike) :

Decorator mode refers to dynamically extending the functionality of an object without having to change the original class files and use inheritance. It wraps the real object by creating a wrapper object, a decoration

Scenario 1

<input />
Copy the code

Browser native Input has no or weak validation, so what do we do now with strong validation — decorator mode

Designed and implemented

All kinds of UI frameworks, such as Element-UI and iView, have been used before. The Input component provided by these frameworks should also be familiar with it. It has friendly interaction and powerful functions. Today our design is going to be a little bit different

Valid-input <valid-input> <input v-model="username" type="text" />
</valid-input>
Copy the code

A quick thought about valid-input:

  • Validate that value
  • What rules are used for validation
// Input is bound to username <valid-input field="username" options="[{rule: required, message: 'username must'}]">
  <input v-model="username" type="text" />
</valid-input>
Copy the code

If ONE day I don’t need validation, I can just delete valid-input, which gives me the flexibility to extend the functionality

Specific implementation process (I wrote an article on related topics before, the link can not be found, if the code implementation needs to be made up later)

Scenario 2

The Checkbox and Radio browsers are ugly and vary from browser to browser, which is unacceptable for a great product

// The normal solution is to checkbox interaction via CSS mode <label class="checkbox-wrapper">
  <span class="checkbox">
    <span class="checkbox-inner"></span>
    <input type="checkbox" class="checkbox-input">
  </span>
  Checkbox
</label>
Copy the code

The realization of such a scene I believe we are not unfamiliar, now the problem is:

I originally used checkbox just <inputtype="checkbox" class="checkbox-input"> < p style = "margin-top: 1em; margin-bottom: 1emCopy the code
Decorator pattern is implemented
// stage. Vue // The implementation of decoratorCheckbox simplifies writing many tags per use and designating class <tempalte> <div> <decorator-checkbox> <inputtype="checkbox" class="checkbox-input">
    </decorator-checkbox>
  </div>
</template>
Copy the code

Specific implementation process (I wrote an article on related topics before, the link can not be found, if the code implementation needs to be made up later)

Third, agent mode

First look at the definition (from Baidu.com) :

A proxy is a category that acts as an interface to something else. A proxy can interface to anything: network connections, large objects in storage, files, or other resources that are expensive or impossible to copy.

UML diagrams of the proxy pattern and decorator pattern look similar. What’s the difference?

Ignorant SAO year like a beautiful gu liang decorator mode: no matter how the gu liang makeup, wear long sleeves or short sleeves (decoration) SAO year each far to watch is gu liang himself agent mode: SAO years according to the restless heart to start action, SAO years thought of a way to first turn gu Liang's friends bestie as their own agent to convey some small note of what, a small note eventually sent to the hands of gu Liang SAO years and can not confirm, but the boy still overnight writing note. See the movie "Hello, China" young ChinaCopy the code

scenario

We got a bunch of data from the back end

  • Data is not null — lists are displayed
  • Data null – Displays an indication that data is null
// list.vue
<template>
 <div>
   <div v-if="isEmpty"> Data is empty </div> <div V-else > <div V-for ="item in data">...do something  
     </div>
   </div>
 </div>
</tempalte>
<script>
  export default{
    props: {
      data: Array
    },
    computed: {
      isEmpty() {
        return this.data.length < 1
      }
    }
  }
</script>
Copy the code

You can see that the List component does two things: data null processing and data non-null processing, which is not a very friendly design

Proxy

// ProxyList.vue
<template>
 <div>
   <empty v-if="isEmpty" />
   <list v-else :data="data" />
 </div>
</tempalte>
<script>
  import Empty from './Empty'
  import List from './List'
  
  export default{
    props: {
      data: Array
    },
    computed: {
      isEmpty() {
        return this.data.length < 1
      }
    },
    components:{
      Empty,
      List
    }
  }
</script>

Copy the code

For the user of data data, just care about taking the data render list, data is empty is not care at all

At the end

This article introduces three design patterns at a time: the adapter pattern, the decorator pattern, and the proxy pattern, and it’s easy to confuse them for the most part, which is why they are grouped together. Take a look at the differences using the examples above

Adapterobjb.methoda () adapterobjb.methoda () adapterobjb.methoda () adapterobjb.methoda ()) decorator mode: Without modifying the original object on the basis of dynamic adding functions function: extend the functionality requirements: decorator to implement proxy pattern and decorative objects the same way: as other objects provide a agent to control access to the object function: requirements: to control access by proxy objects like the decorator pattern to achieve and by proxy objects the same wayCopy the code

This implementation also applies to react. Why vue? The React JSX template can be a bit awkward to understand, while the React JSX template can be seen as writing JavaScript to implement more flexible concepts