1, Agent mode
1.1. Basic introduction
- 1. Proxy mode: provides an avatar for an object to control access to the object. That is to access the target object through the proxy object. The benefits of this can enhance additional function operations on the basis of the realization of the target object, that is, expand the function of the target object.
- 2. The proxied object can be a remote object, an object with high creation cost, or an object requiring security control.
- 3. There are three kinds of proxy modes: static proxy, dynamic proxy (JDK proxy, interface proxy) and Cglib proxy (you can dynamically create objects in memory without implementing interfaces. It belongs to the category of dynamic proxy).
1.2. Schematic diagram
2, Static proxy
2.1. Basic introduction
- When using a static proxy, you need to define an interface or parent class. The proxy object (i.e. the target object) implements the same interface or inherits the same parent class with the proxy object.
2.2. Schematic diagram
- 1. Define an interface: ITeacherDao.
- 2. The target object TeacherDAO implements the interface ITeacherDAO.
- 3. Using the static proxy method, you need to implement ITeacherDAO in the proxy object TeacherDAOProxy.
- 4. When called, the target object is called by calling the method of the proxy object.
- 5. Special reminder: the proxy object and the target object should implement the same interface, and then call the method of the target object by calling the same method.
2.3. Code implementation
- Interface
public interface ITeacherDao { void teach(); // Teaching methods }
- Target object
public class TeacherDao implements ITeacherDao { @Override public void teach() { System.out.println(" The teacher is teaching....."); } }
- Proxy object
public class TeacherDaoProxy implements ITeacherDao { private ITeacherDao target; // Target object, aggregated through interface public TeacherDaoProxy(ITeacherDao target) { this.target = target; } @Override public void teach() { System.out.println("Start agent to complete some operations..... ");//method target.teach(); System.out.println("Submit.....");//method } }
- client
public class Client { public static void main(String[] args) { //Create target object (proxied object) TeacherDao teacherDao = new TeacherDao(); //Create a proxy object and pass the proxy object to the proxy object at the same time TeacherDaoProxy teacherDaoProxy = new TeacherDaoProxy(teacherDao); //Through the proxy object, call the method to the proxy object // That is, the method of the proxy object is executed, and the proxy object calls the method of the target object teacherDaoProxy.teach(); } }
- output
Start agent to complete some operations.....
The teacher is teaching.....
Submit.....
2.4. Advantages and disadvantages of static agent
- 1. Advantages: the target function can be extended through the proxy object without modifying the function of the target object.
- 2. Disadvantages: because the proxy object needs to implement the same interface as the target object, there will be many proxy classes.
- 3. Once a method is added to the interface, both the target object and the proxy object must be maintained.
3, Dynamic agent
3.1. Basic introduction
- 1. The proxy object does not need to implement the interface, but the target object must implement the interface, otherwise the dynamic proxy cannot be used.
- 2. The generation of proxy object is to dynamically build proxy object in memory by using JDK API.
- 3. Dynamic agent is also called JDK agent and interface agent.
3.2. API for generating proxy object in JDK
- 1. Package of proxy class: java.lang.reflect.Proxy.
- 2. The JDK implementation agent only needs to use the newProxyInstance method, but this method needs to receive three parameters. The complete writing method is: static object newProxyInstance (classloader, class <? > [] interfaces, invocationhandler h).
3.3. Schematic diagram
- Note: using reflection mechanism
3.4. Code implementation
- Interface
public interface ITeacherDao { void teach(); // Teaching methods void sayHello(String name); }
- Target object
public class TeacherDao implements ITeacherDao { @Override public void teach() { System.out.println(" The teacher is teaching....."); } @Override public void sayHello(String name) { System.out.println("hello " + name); } }
- Agent factory
/**
* public static Object newProxyInstance(
* ClassLoader loader,
* Class<?>[] interfaces,
* InvocationHandler h)**/
//1. Classloader: Specifies the class loader used by the current target object, and the method to obtain the loader is fixed
//2. Class<?> [] interfaces: the interface type implemented by the target object. Use the generic method to confirm the type
//3. InvocationHandler h: event processing. When executing the method of the target object, the event handler method will be triggered, and the currently executed target object method will be passed in as a parameter
public class ProxyFactory { //Maintain a target Object, Object private Object target; public ProxyFactory(Object target) { this.target = target; } public Object getProxyInstance() { /** * public static Object newProxyInstance( * ClassLoader loader, * Class<?>[] interfaces, * InvocationHandler h)**/ //1. Classloader: Specifies the class loader used by the current target object, and the method to obtain the loader is fixed //2. Class<?> [] interfaces: the interface type implemented by the target object. Use the generic method to confirm the type //3. InvocationHandler h: event processing. When the method of the target object is executed, the event handler method will be triggered, //The currently executed target object method will be passed in as a parameter return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("JDK Agent start~~"); //The reflection mechanism calls the method of the target object Object returnVal = method.invoke(target, args); System.out.println("JDK Proxy submission"); return returnVal; } }); } }
- client
public class Client { public static void main(String[] args) { //Create target object ITeacherDao target = new TeacherDao(); //Create a proxy object for the target object, which can be converted to ITeacherDao ITeacherDao proxyInstance = (ITeacherDao)new ProxyFactory(target).getProxyInstance(); // proxyInstance=class com.sun.proxy.$Proxy0 dynamically generates proxy objects in memory System.out.println("proxyInstance=" + proxyInstance.getClass()); //The method of the target object is called through the proxy object // proxyInstance.teach(); proxyInstance.sayHello(" tom "); } }
- output
proxyInstance=class com.sun.proxy.$Proxy0
JDK agent start~~
hello tom
JDK proxy submission
4, Cglib agent
3.1. Basic introduction
- 1. Both static proxy and JDK proxy modes require the target object to implement an interface, but sometimes the target object is only a separate object and does not implement any interface. At this time, the target object subclass can be used to implement the proxy - this is Cglib proxy.
- 2. Cglib agent is also called subclass agent. It constructs a subclass object in memory to expand the function of the target object. Some books also attribute cglib agent to dynamic agent.
- 3. Cglib is a powerful high-performance code generation package. It can extend java classes and implement java interfaces at runtime. It is widely used by many AOP frameworks, such as Spring AOP, to implement method interception.
- 4. How to select proxy mode in AOP programming:
The target object needs to implement the interface and use JDK proxy
The target object does not need to implement the interface and uses Cglib proxy
- 5. The bottom layer of Cglib package is to convert bytecode and generate new classes by using bytecode processing framework ASM.
3.2. Implementation steps of cglib proxy mode
- You need to import the jar file of cglib
- Dynamically build subclasses in memory. Note that the class of the proxy cannot be final. Otherwise, an error java.lang.IllegalArgumentException will be reported.
- If the method of the target object is final/static, it will not be intercepted, that is, additional business methods of the target object will not be executed.
3.3. Schematic diagram
3.4. Code implementation
5, Introduction to several common proxy patterns – several variants
- 1. Firewall agent
The intranet penetrates the firewall through the agent to realize the access to the public network.
- 2. Cache agent
For example, when requesting resources such as picture files, go to the cache agent first. If you get the resources, ok. If you can't get the resources, go to the public network or database, and then cache.
- 3. Remote proxy: the local representative of a remote object, through which the remote object can be called as a local object. Remote agents communicate information with real remote objects through the network.
- 4. Synchronization agent: it is mainly used in multithreaded programming to complete the synchronization between multithreads.