The design patterns used by vue: 1. Singleton mode ensures that a class has only one instance object and provides a global access point for its access. 2. Factory pattern is a pattern used to create objects. It is not necessary to expose the specific logic of the constructor, but to encapsulate the logic in each function. 3. Decorator mode allows adding new functionality to existing functions without changing its structure. 4. Strategy pattern is to define a series of algorithms, encapsulate them one by one, and make them interchangeable. 5. Publish-subscriber model.
The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.
The principle of design pattern is to find changes in the program and encapsulate the changes to achieve efficient reusability. The core is intention, not structure. Design patterns can help us enhance the reusability, scalability, maintainability, and flexibility of code. Our ultimate goal in using design patterns is to achieve high clustering and low coupling of the code. Have you ever thought about this question, how to make code more robust? In fact, the core lies in grasping change and immutability. Ensure that the changing parts are more flexible and the unchanged parts are more stable, and using design patterns allows us to achieve this goal.
Let’s summarize the design patterns commonly used in vue projects or work.
Single case mode: Ensure that a class has only one instance object and provide a global access Click for access.
Advantages: Applicable to a single object, only one object instance is generated, avoiding frequent creation and destruction of instances, and reducing memory usage.
Disadvantages: Not applicable to dynamically extended objects.
Scenario: Login floating window, axios instance in Vue (we perform request interception and response interception on axios, call the encapsulated axios multiple times but only set it once, the encapsulated axios Export is a singleton), global state management store, thread pool, global cache
function Person (name, age) { this.name = name this.age = age this.info = function () { console.log(`我的名字叫${this.name}, 我今年${this.age}了`) } } Person.getInstance = function (name, age) { if (!this.instance) { this.instance = new Person(name, age) } console.log(this.instance) return this.instance } let b1 = Person.getInstance('单例1', 18) let b2 = Person.getInstance('单例2', 18) b1.info() b2.info()
Factory mode: Factory mode is One of the most common design patterns used to create objects. It is not necessary to expose the specific logic of the constructor, but to encapsulate the logic in each function, then this constructor can be regarded as a factory.
Scenario: Where there is a constructor, a lot of constructor code is written and a lot of new operators are called.
Advantages: Through the factory pattern, we can quickly create a large number of similar objects without duplicating code.
Disadvantages: The objects created by the factory pattern belong to Object, and the object type cannot be distinguished. This is why the factory pattern is not widely used.
function Factory (name, age) { this.name = name; this.age = age; // 或者 // let obj = {} // obj.name = name // obj.age = age // return obj } Factory.prototype.say = function () { console.log(`我的名字叫${this.name}, 我今年${this.age}了`) } let zs = new Factory('张三', 18); let ls = new Factory('李四', 20); zs.say() ls.say()
Decorator Mode (Aspect Programming AOP): Without changing the basis of the object itself On the other hand, responsibilities are dynamically added to the object during the running of the program; if the function body is directly modified, it violates the 'open and closed principle' and also violates our 'single responsibility principle'; to put it simply, it allows adding to existing functions. new functionality without changing its structure.
Scenario: Form validation and form submission in vue use this model and follow the closed and open principle.
function before (fn, callback) { let _this = this; return function () { callback.apply(this, arguments) return fn.bind(this, arguments) } } function after (fn, callback) { let _this = this return function () { let res = fn.apply(this, arguments) callback.apply(this, arguments) return res } } // before和after是两个高阶函数,让我们一起回忆一下什么是高阶函数? // 还知道call,apply,bind的区别吗 let getName = function getName () { // 加入这是你同事写的烂代码,看不下去的那种,那么别动他的代码 console.log('这是getName函数') } before(getName, function () { // 这个就是你要写的新逻辑 console.log('切入前代码') })() after(getName, function () { // 这个也是你要写的新逻辑 console.log('切入后代码') })()
Strategy Mode: It is to define a series of algorithms and encapsulate them one by one. And make them interchangeable.
let strategy = { 'A': function (bonus) { return bonus * 4 }, 'B': function (bonus) { return bonus * 3 } } function fn (level, bonus) { return strategy[level](bonus) } let result = fn('A', 4000) console.log(result, 'result') // 策略模式提供了开放-封闭原则,将算法或者方法封装在一个类中,使它们易于切换,易于替换。 function func (a, b) { let f = function f() { return a + b } return f }
You can also use it in vue form validation
// 这里可以将所有的表单验证正则函数写在这里 export const loginUsername = (str) => { return /^[a-zA-Z0-9_]{3,20}$/.test(str); };
import * as validateForm from './validate'; export const gene = (key, msg) => { return (r, v, c) => { if (validateForm[key](v)) { c(); } else { c(new Error(msg)); } }; };
// 这样看着是不是很清晰明了 import {gene} from '@/utils/formValidateGene'; rules: { account: [{ required: true, validator: gene('loginUsername', '请输入合适的账号'), trigger: ['blur', 'change'] }] }
Publish subscriber Pattern is also called Observer Pattern, Publish Subscriber PatternA one-to-many dependency relationship. When the state of an object changes, all objects that depend on it Everyone must be notified; Observer pattern is a one-to-one dependency relationship.
class Observer { client = {} // 订阅 listen (key, fn) { if (!this.client[key]) { this.client[key] = [] } this.client[key].push(fn) } // 发布 publish (key) { this.client[key].forEach(fn => { fn.apply(this, arguments) }) } } let observer = new Observer() observer.listen('华为', (model, brand) => { console.log(model, brand) }) observer.listen('苹果', function (model, brand) { console.log(model, brand) }) observer.publish('华为', 'P50') observer.publish('苹果', '14')
class EventEmitter { constructor () { this.client = {} } on (key, fn) { if (!this.client[key]) { this.client[key] = [] } this.client[key].push(fn) } trigger (key, ...args) { this.client[key].forEach(cb => cb(...args)) } } let event = new EventEmitter() event.on('hello', function(res) { console.log('hello', res) }) let data = { name: '测试' } Object.defineProperty(data, 'name', { get (val) { // console.log(val) }, set (newVal) { console.log(newVal) event.trigger('hello', newVal) } }) data.name = '正在测试'
[Related recommendations: vuejs video tutorial、web front-end development】
The above is the detailed content of What modes does vue use?. For more information, please follow other related articles on the PHP Chinese website!