Objective:
Recently in the study of retrofit open source framework, its main core code is through annotated parameters, dynamic proxy mode implementation of specific interfaces, reflection mechanism for parameter resolution, the final implementation of sending requests. In fact, before learning Xutils source code, Xutils's task is also through the proxy mode to access. Why should we adopt a proxy model? What good is it? Hold on to these questions! Come and learn to summarize today.
What is proxy mode?
Proxy mode definition: The proxy mode provides a proxy object to an object, and the proxy object controls the reference to the original object. For example, one person or one institution acts on behalf of another person or another body. In some cases, a client does not want or cannot refer directly to an object, whereas a proxy object can act as an intermediary before the client and the target object.
Examples of application scenarios:
Through the proxy mode described above we can know that the purpose is to control the object reference, life scenes in our car for example, if we want to buy a car must pass the car 4S shop, car 4s shop is acting as a proxy role, the purpose is to control the purchase of car customers car behavior, It is necessary to buy a car from a car manufacturer through a 4S shop.
1.) First create a new interface to buy a car
Public interface Ibuycar { //buy car void Buycar ();}
2.) Declare a customer to buy a car, to achieve the car interface
Public classCustomerImplementsIbuycar {Private intCash//Car Purchase Public intGetCash () {returncash; } Public voidSetcash (intCash) { This. Cash =cash; } @Override Public voidBuycar () {LOG.E ("Buycar", "buy a car cost--" + Cash + "Yuan"); }}
3.) Declare a car dealership 4S shop, also realize the purchase of car interface, must accept customer orders
Public class Implements ibuycar{ private customer customer; receive a car customer public buycarproxy (Customer customer) { this. Customer=customer; // receiving customers for buying cars } @Override publicvoid Buycar () {// implement buying a car for a customer Customer.buycar (); }}
4.) Create a client to simulate a car purchase
Customer Customer=new customer (); Customer.setcash (120000); Buycarproxy buycarproxy=new buycarproxy (customer); Buycarproxy.buycar ();
5.) Access control via proxy mode
Through the above example, we may have a question, can't we go directly to the manufacturer to buy a car? Of course, if the implementation of the class in the use scenario can meet the requirements, we can certainly directly implement the class, but when the implementation class can not meet the requirements, to expand the requirements, according to the opening and closing principle you can not modify the implementation of Class code, then you use the proxy class. For example, to buy a car we have to carry out a purchase to the customer audit, if meet the conditions to buy a car, do not meet the requirements of our customers to inform the lack of purchase money.
@Override Public void Buycar () {// implemented for customer buy car int cash=customer.getcash (); if (cash<100000) { log.e ("Buycar", "You don't have enough money to buy a car") ; return ; } Customer.buycar (); }
Implementation scenarios
Customer customer=New customer (); Customer.setcash (120000); Buycarproxy buycarproxy=new=new Customer (); Customer1.setcash (90000 =new buycarproxy (customer1); Buycarproxy1.buycar ();
Dynamic agent mechanism:
The above is the static implementation of the proxy mode, the so-called static proxy is to be the proxy class to write a proxy class, or use the tool for its generated proxy class, in short, the program has already existed before the compilation of good proxy class, so sometimes feel very troublesome, also lead to very inflexible, compared to static agent, Dynamic proxies are more flexible because they do not have to specify a proxy class to proxy the proxy object when we design the implementation, and we can defer this designation until the runtime is implemented by the JVM.
Example: or follow the example above
1.) First we declare a dynamic proxy class to implement the Invocationhandler interface
Public classDynamicproxyImplementsInvocationhandler {//instances of the class being proxiedObject obj; //passing an instance of a proxy into the constructor of a dynamic proxy class Publicdynamicproxy (Object obj) { This. obj =obj; } /*** Overwrite the Invoke () method in the Invocationhandler interface * More importantly, the dynamic proxy pattern allows us to extend, enhance, and achieve the original "real method" without altering the original code structure *. * Control the behavior of the agent object, the following before, after is we can make special * code to cut into the extension point. */ Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {/** before:dosomething (); */Object Result= Method.invoke ( This. obj, args); /** after:dosomething (); */ returnresult; }}
2.) Specific implementation
//the real object we're going to be acting forCustomer customer =NewCustomer (); //we're going to proxy which real object, we'll pass the object in, and finally we'll call its method through the real object .Invocationhandler handler =NewDynamicproxy (customer); /** Using Proxy's Newproxyinstance method to create our proxy object, let's take a look at its three parameters * the first parameter Handler.getclass (). getClassLoader (), which we use here Handler this class of ClassLoader object to load our proxy object * The second parameter Customer.getclass (). Getinterfaces (), the interface that we provide for the proxy object is the interface that the real object implements. I'm going to represent the real object, so I can invoke the method in this set of interfaces * The third parameter handler, where we associate this surrogate object to the Invocationhandler above*/Ibuycar Buycar=(Ibuycar) proxy.newproxyinstance (Handler.getclass (). getClassLoader (), Customer.getclass (). GetInterfaces (), handler); Buycar.buycar ();
3.) Dynamic Agent Benefits
Benefits of using the Java Dynamic Agent mechanism:
1, reduce the workload of programming: if you need to implement a variety of agent processing logic, as long as write multiple agent processor on it, no need to write a proxy class each way.
2, System expansion and maintenance enhancements, the program is also more convenient to modify (generally as long as the agent processor class on the line).
Summarize:
Through the application examples above we have learned the specific usage scenarios of the proxy mode.
Proxy mode for Java design mode