Agent model of design pattern combing

Sorting is always from easy to difficult, and the agent mode is not difficult to understand, because the front-end partners are commonly used agents. Today, sort out the so-called agent mode

What is the agent model

Agent mode is very common. Not only do we see the so-called agent mode in our life, brokers, secretaries, lawyers, including investment managers, all belong to the embodiment of the agent mode, but also look at the actual embodiment in our code, such as host, server agent i request, vue two-way binding core, VPN tool, which belong to agents. What are the commonalities of agents, That is to find a substitute object for an object in order to access the original object. As for why there should be a substitute object, we can see from the above example why there is a broker Secretary to invest energy, host The emergence of alternative objects such as VPN tools is simply that the original object cannot complete some functions. It can be completed for him through the interception of the agent, so that the object can be used normally. Sometimes i think that the agent is the same as the extension. In fact, the core of the agent is interception

  • intercept
    Why do we say that the core of proxy is interception? When we want to replace the original object to do something, we must intercept what we have done to the original object, or what we need to do to the original object. Interception is essential. Some logic like proxy mode does not have the so-called get and set interception, but encapsulates a method for the object, When calling an object to change data and other operations, in order not to change the original object, the encapsulated logic is directly called. In fact, I think this encapsulated logic is also a proxy mode: take chestnuts for example

Examples are as follows. To explain from the perspective of thought, the example reduced to the extreme does not mean that it is the case in practical application

//Programmers eat

//restaurant
restaurant{
	'Tomato and egg covered rice':15,
	'Rice with shredded pork and pepper':18,
	'Braised beef noodle':25
}


//Now the programmer is coming to dinner
restaurant['Braised beef noodle']
//Then get the price, find it is 25, and then buy it

Programmers go directly to the restaurant to order and get food without any intermediate way, so it doesn't seem to be an agent

//It's a rule to add two pieces of shredded meat and pepper on Saturday
funtion proxyRest(name){
	let data = new Date().getDay()
	if( data === 6 && name === 'Rice with shredded pork and pepper' ){
		return restaurant[name]+2
	} else{
		return restaurant[name]
	}
}

If we abandon the agent of the object itself and only start from the most primitive logic, we will add an additional method. In the future, when programmers eat, they will no longer directly call the object of the restaurant to obtain, but know how much to pay through the method. This method is equivalent to an agent. When accessing the object, they will pass through the agent layer, Judge in the middle, visit the object, or change it, and become a better understanding between the boss and the store manager

//The boss runs a restaurant
funtion Boss(){
	this.restaurant{
		'Tomato and egg covered rice':15,
		'Rice with shredded pork and pepper':18,
		'Braised beef noodle':25
	}
	return restaurant['Braised beef noodle']
}
//The boss manages the store on behalf of the store manager
funtion Boos(){
	return shopowner(name)
}

funtion shopowner(name){
	this.restaurant{
		'Tomato and egg covered rice':15,
		'Rice with shredded pork and pepper':18,
		'Braised beef noodle':25
	}
	let data = new Date().getDay()
	if( data === 6 && name === 'Rice with shredded pork and pepper' ){
		return restaurant[name]+2
	} else{
		return restaurant[name]
	}
}

If you want to buy something directly from the boss, the boss said, I'll ask the store manager to arrange what you want, and the store manager will judge and return. This is the job represented by the store manager

Proxy

Some people will say whether this is too troublesome. Of course, the Proxy is not suitable for use at all times, and all design patterns are not suitable for all places. We will talk about the Proxy mode. One thing that is very easy to use and fully follows the Proxy mode is Proxy, which is in vue3 0. We mainly talk about Proxy's use of Proxy mode

The concept of Proxy in ES6 is that it is used to modify the default behavior of some operations, which is equivalent to making modifications at the language level. Therefore, it belongs to a kind of "meta programming", that is, programming the programming language. It's easy to understand why we should make changes from the basic level of language. Let's see

var objProxy = new Proxy(obj, {
  get: function (target, propKey, receiver) {
  	.............
  },
  set: function (target, propKey, value, receiver) {
    .............
  }
});

get and set are interceptions when attributes are taken out for use and inserted for change. These two methods can be rewritten directly in es6 syntax to achieve the purpose of interception. This is also mentioned

  • Authentication agent
    1. Verify the data
    There is no need to repeat this. From the above set method, we can see that we can carry out a series of logical processing during set operation, and then carry out logical processing in set is to verify the agent
    Another corresponding interception of get operation is the private attribute proxy, which is to make logical judgment to see whether data reading is allowed
//Borrow the code of online form verification agent
const getValidateProxy = (target, validators) => {
  return new Proxy(target, {
    _validators: validators,
    set(target, prop, value) {
      if (value === '') {
        console.error(`"${prop}" is not allowed to be empty`);
        return target[prop] = false;
      }
      const validResult = this._validators[prop](value);
      if(validResult.valid) {
        return Reflect.set(target, prop, value);
      } else {
        console.error(`${validResult.error}`);
        return target[prop] = false;
      }
    }
  })
}
  • Cache agent
    1. Acting on the method
//cache is regarded as the stored key value pair of the previously passed in parameters and the calculated data
var objProxy = new Proxy(fn, {
 apply(target, context, args) {
      const argsString = args.join(' ');
      if (cache.has(argsString)) {
        // If there is a cache, directly return the cached data
        return cache.get(argsString);
      }
      const result = fn(...args);
      //If there is no cache, it is stored in the cache and the calculation result is returned
      cache.set(argsString, result);
      return result;
    }
});

The advantage of this is that for some extremely complex computing logic, you can use the cache method to reduce the actual call of computing logic. To say, can you call the cache before calling the method each time, and then add this logic to each calculation in the method? Yes, it is not elegant. Therefore, it can be seen that all design patterns are designed to save trouble and make the logic clear

Keywords: Javascript TypeScript Vue.js Design Pattern

Added by jds580s on Sun, 06 Mar 2022 17:57:31 +0200