In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what is the agency mode". In the operation of the actual case, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Agent mode
The whole process is shown in code as follows:
/ * shoes factory interface * / public interface IShoesFactory {/ * visit the factory * / void visitFactory (); / * place an order * @ param price amount * / void placeOrder (double price); / * delivery * / void ship ();} / * * shoes factory * / public class ShoesFactory implements IShoesFactory {private String name Public ShoesFactory (String name) {this.name = name;} / * visit the factory * / @ Override public void visitFactory () {System.out.println ("show customers around" + name) } / * place order * * @ param price amount * / @ Override public void placeOrder (double price) {System.out.println ("receive" + price + "Yuan order");} / * Shipping * / @ Override public void ship () {System.out.println ("start shipping") Agent shoes factory * / public class ShoesFactoryProxy implements IShoesFactory {private IShoesFactory shoesFactory; public ShoesFactoryProxy (IShoesFactory shoesFactory) {this.shoesFactory = shoesFactory;} / * visit the factory * / @ Override public void visitFactory () {shoesFactory.visitFactory () } / * * place order * * @ param price amount * / @ Override public void placeOrder (double price) {shoesFactory.placeOrder (price);} / * Shipping * / @ Override public void ship () {shoesFactory.ship ();}}
Customer category:
Public class Client {public static void main (String [] args) {IShoesFactory factory = new ShoesFactory ("Liu Wangxing's factory"); IShoesFactory factoryProxy = new ShoesFactoryProxy (factory); / / visit the factory factoryProxy.visitFactory (); / / place an order factoryProxy.placeOrder (10000); / / ship factoryProxy.ship ();}}
Output result:
Show customers around Liu Wangxing's factory and receive an order of 10000.0 yuan to start delivery.
When the customer wanted to visit the factory, Xiao Shuai took the customer to visit Liu Wangxing's factory and told the customer that this was his factory. The customer issued an order to Xiao Shuai, and Xiao Shuai placed the order to Liu Wangxing.
The client class calls the method of the proxy, and the proxy class invokes the method of the business class to complete the work.
Agent pattern definition
Proxy pattern (Proxy Pattern): provides a proxy to an object, and the proxy object controls the reference to the original object. Agent mode is called Proxy in English. It is a structural model.
There is generally at least one actual object behind the agent, and the external function of the agent is generally the same as the actual object. Users deal with the agent, do not directly contact the actual object, or even do not know the existence of the actual object.
What is the use of the agent model? Is it just a forwarding through the proxy class?
Of course not. Although the external function is the same as the actual object, the agent has its existence value, and the agent can be divided into many types, such as:
Remote proxy: suitable for calling remote server objects, the agent transmits client requests through the network, handles all the complex details related to the network, and simplifies client calls.
Virtual proxy: if you need to create a resource-intensive object, create a relatively low-cost object to represent it, and the real object will only be created when needed.
Copy-on-Write agent: it is a type of virtual agent that delays replication (cloning) operations until it is really needed by the client. In general, deep cloning of objects is an expensive operation, and the Copy-on-Write agent can delay this operation and be cloned only when the object is used.
Protect or Access agent: controls access to an object and provides different levels of permissions to different users.
Cache proxy: provides temporary storage space for the results of a target operation so that multiple clients can share the results.
Firewall (Firewall) proxy: protects the target from malicious users.
Synchronization proxy: enables several users to use an object at the same time without conflict.
Intelligent reference (Smart Reference) proxy: when an object is referenced, it provides some additional operations, such as recording the number of times the object is called.
Let's look at a few examples:
Protection agent
The role of the Protect or Access agent is to control access to an object and to provide different levels of permissions to different users.
If we don't want customers to access a function, we can tamper with the proxy class. After all, business classes are called through the proxy class.
For example, the handsome boy is afraid of revealing and does not want his customers to visit the factory, so he can rewrite the method of visiting the factory:
Output:
The factory forbids visiting and receives an order of 10000.0 yuan to start shipping intelligent quoting agent.
The role of the Smart Reference agent is to provide additional operations when an object is referenced, such as recording the number of times the object is called.
For example, Xiao Shuai, as an agent, is sure to make money. When a customer places an order of 10000 yuan, Xiao Shuai talks with Liu Wangxing about a commission of 10%, and the amount can be deducted from the agent category.
Also, Xiao Shuai's factory has its own brand, and it has to be affixed with its own brand before delivery.
Output:
The factory forbids visitors to receive orders worth 9000.0 yuan and label them as handsome. Several applications of initial Shipping Agent Mode
Image proxy: a common application example of an agent mode is the control of large image browsing. When users visit the web page through the browser, they do not load the real large image first, but deal with it through the method of proxy object.
In the method of the proxy object, a thread is used to load a small picture to the client browser, and then another thread is used in the background to call the load method of the large picture to load the large picture to the client. When you need to view a large picture, display the big picture on the new web page.
If the loading is not finished while browsing the large image, you can start another thread to display the appropriate prompt. Through the agent technology combined with multithreaded programming to load the real picture to the background to operate, does not affect the browsing of the foreground picture.
Remote agent: the remote agent can hide the details of the network so that the client does not have to consider the existence of the network. Customers can think that the proxied remote business object is local rather than remote, and the remote agent object undertakes most of the network communication work.
Virtual proxy: when the loading of an object is very resource-consuming, the advantage of virtual proxy is very obvious. Virtual proxy mode is a memory-saving technique, and the creation of objects that take up a lot of memory or deal with complex objects will be deferred until it is used.
Dynamic agent
The methods mentioned above are static proxy patterns, and the real business class must be created in advance and passed to the proxy object as an internal member.
Static proxies look like this:
If a real business class must correspond to a proxy class, this will lead to a sharp increase in the number of proxy classes in the system, for example, if there are 10 different business classes, then there must be 10 corresponding proxy classes. therefore, we need to find a way to reduce the number of classes in the system.
The dynamic agent can use the agent class without knowing the real business class in advance, and it is dynamically generated by JVM according to the reflection mechanism during the program running. the typical application of the dynamic agent is Spring AOP.
Let's take a look at an example of a Java SDK dynamic proxy:
/ * shoes factory interface * / public interface IShoesFactory {/ * visit the factory * / void visitFactory (); / * place an order * @ param price amount * / void placeOrder (double price); / * delivery * / void ship ();} / * * shoes factory * / public class ShoesFactory implements IShoesFactory {private String name Public ShoesFactory (String name) {this.name = name;} / * visit the factory * / @ Override public void visitFactory () {System.out.println ("show customers around" + name) } / * place order * * @ param price amount * / @ Override public void placeOrder (double price) {System.out.println ("receive" + price + "Yuan order");} / * Shipping * / @ Override public void ship () {System.out.println ("start shipping");}}
The InvocationHandler interface is an interface implemented by the call handler of the proxy proxy instance, and the proxy class enters the invoke method here each time the method is called.
Public class ShoesFactoryHandler implements InvocationHandler {/ * proxied object, actual method executor * / private Object proxiedObject; public ShoesFactoryHandler (Object proxiedObject) {this.proxiedObject = proxiedObject The proxy class will enter here every time the method is called. * @ param proxy represents the proxy object itself, which should be noted. It is not the object being proxied * @ param method represents the method being called * @ param args represents the parameter of the method * @ return * @ throws Throwable * / @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {/ * if (method.getName (). Equals ("visitFactory")) {System.out.println ("Factory prohibited") } * / if (method.getName (). Equals ("placeOrder")) {/ / if it is an order placing method, give the factory a 10% discount on the price method.invoke (proxiedObject, Double.parseDouble (String.valueOf (args [0])) * 0.9) } else if (method.getName (). Equals ("ship")) {/ / if it is a shipping method, label System.out.println ("tag handsome") before shipment; method.invoke (proxiedObject, args);} else {/ / other methods, call method.invoke (proxiedObject, args) directly } return null;}}
The Proxy class calls the newProxyInstance method to create a proxy object, with the above InvocationHandler object as one of the parameters.
Public class ShoesFactoryProxy {/ * generates dynamic proxy * @ param proxiedObject objects proxied, and the actual method executor * @ return * / public Object createProxy (Object proxiedObject) {/ / gets the corresponding ClassLoader ClassLoader classLoader = proxiedObject.getClass () .getClassLoader (); / / gets all interfaces Class [] interfaces = proxiedObject.getClass () .getInterfaces () / / create a call request handler ShoesFactoryHandler handler = new ShoesFactoryHandler (proxiedObject) passed to the proxy class; return Proxy.newProxyInstance (classLoader, interfaces, handler);}}
Client class:
Public class Client {public static void main (String [] args) {IShoesFactory factory = new ShoesFactory ("Liu Wangxing's factory"); ShoesFactoryProxy shoesFactoryProxy = new ShoesFactoryProxy (); IShoesFactory factoryProxy = (IShoesFactory) shoesFactoryProxy.createProxy (factory); / / visit the factory factoryProxy.visitFactory (); / / place an order factoryProxy.placeOrder (10000); / / ship factoryProxy.ship ();}}
Output result:
Show customers around Liu Wangxing's factory, receive an order of 9000.0 yuan, put a handsome label on it and start shipping.
The more versatile dynamic proxy classes generally look like this:
Public class NormalHandler implements InvocationHandler {/ * proxied object, actual method executor * / private Object proxiedObject; public NormalHandler (Object proxiedObject) {this.proxiedObject = proxiedObject The proxy class will enter here every time the method is called. * @ param proxy represents the proxy object itself, which should be noted. It is not the object being proxied * @ param method represents the method being called * @ param args represents the parameter of the method * @ return * @ throws Throwable * / @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {/ / the operation preRequest () before calling the actual method / / call the actual method Object result = method.invoke (proxiedObject, args); / / the operation after calling the actual method afterRequest ();} return result;}}
In this way, we can do a lot of things in the preRequest () and afterRequest () methods, such as logging, recording the call time, and so on.
Summary
The proxy pattern looks very similar to the decorator pattern, but their intentions are not the same. The decorator pattern is to add new behavior to the object, while the proxy pattern is to act as a stand-in for the real object and control the access to the object.
For example, protect the agent, carry out permission control, and prevent customers from accessing certain functions; for example, virtual agents return predetermined information before the real object is created.
Let's take a look at the pros and cons of the proxy model:
Advantages
The agent mode can coordinate the caller and the callee, which reduces the coupling degree of the system to a certain extent.
You can control the service object without the client knowing it.
The agent can work properly even if the service object is not ready or does not exist.
In accordance with the open-close principle, you can create a new proxy without making changes to the service or client.
Shortcoming
Due to the addition of proxy objects between the client and the real business class, some types of proxy patterns may slow down the processing of requests.
The implementation of the agent mode requires extra work, which increases the complexity of the program.
This is the end of "what is the Agent Mode". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.