Java static proxy and dynamic proxy

Original link: http://www.orlion.ga/207/

1、 Agent mode

Proxy pattern is a frequently used design pattern. Proxy pattern provides proxy objects for specified objects. The reference of specific objects is controlled by proxy objects.

Roles involved in agent mode:

Abstract topic role: it declares the public interface between proxy topic and real topic, so that any place where real topic is needed can be replaced by proxy topic.

(design patterns are generic)

According to the creation period of the agent, the agent class can be divided into two types:

Static agent: it is created by programmers or automatically generated by specific tools, and then compiled. The of the proxy class before the program runs The class file already exists.

Dynamic agent: it is created dynamically by using reflection mechanism when the program is running.

2、 Static proxy

Talk is cheap,show me the code

First, define the interface of a winery:

WineFactory. java

    package ml.orlion.proxy;    
    
    public interface WineFactory {
    
    	public void sell();
    }

Then define a winery class to implement this interface:

WineFactoryImpl. java

    package ml.orlion.proxy;

    public class WineFactoryImpl implements WineFactory{
    
    	@Override
    	public void sell() {
    		System.out.println("卖酒");
    	}
    	
    }

Then define an agent class to represent the winery:

WineFactoryProxy. java

    package ml.orlion.proxy;
    /**
     * 代理类
     * 对WineFactoryImpl进行代理
     */
    public class WineFactoryProxy implements WineFactory{
    	
    	private WineFactory winef;
    
    	public WineFactoryProxy(WineFactory winef){
    		this.winef = winef;
    	}
    
    	@Override
    	public void sell() {
    		System.out.println("卖酒之前...");
    		winef.sell();
    		System.out.println("卖酒之后...");
    	}
    }

3、 Dynamic agent

From the code of the static agent, you can see that the static agent can only serve one interface. If there are many interfaces in the project, too many agents will be generated. At this time, we need to use dynamic proxy, and a proxy class completes all proxy functions. The bytecode of dynamic proxy class is dynamically generated by java reflection mechanism when the program is running, and there is no need for programmers to write its source code manually. Dynamic proxy class not only simplifies programming, but also improves the scalability of software system, because java reflection mechanism can generate any type of dynamic proxy class.

JDK dynamic proxy includes an invocationhandler interface and a proxy class

(1) Invocationhandler interface

    public interface InvocationHandler {     
        public Object invoke(Object proxy,Method method,Object[] args) throws Throwable; 
    }

Where object porxy: is the proxy object

Method: method to call

Object [] args: parameters of the method to be called

(2) Proxy class

Proxy class is an operation class dedicated to proxy, which can be used to dynamically generate implementation classes for one or more interfaces. This class provides the following operation methods:

    public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,     InvocationHandler h)  throws IllegalArgumentException

Where classloader: is the class loader;

(there are three main types of loaders in Java:

Boost strap classloader: this loader is written in C + +, which is invisible in general development;

Extension classloader: used to load extension classes, generally corresponding to classes in jrelibext directory;

Appclassloader: (default) loads the class specified in classpath. It is the most commonly used loader.

Class [] interfaces: get all interfaces;

Invocationhandler H: get the subclass instance of invocationhandler interface;

code:

WineFactory. Java and winefactoryimpl Java and static proxy have the same code.

WineFactoryInvocationHandler. java:

    package ml.orlion.proxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    /**
     * JDK动态代理类
     * 对WineFactoryImpl进行代理
     */
    public class WineFactoryInvocationHandler implements InvocationHandler{
    
    	private Object target;
    
    	@Override
    	public Object invoke(Object porxy, Method m, Object[] args) throws Throwable {
    		
    		Object result = null;
    		
    		beforeMethod();
    		// 执行
    		result = m.invoke(target, args);
    		
    		afterMethod();
    		return result;
    	}
    	
    	public void beforeMethod(){
    		System.out.println("卖酒之前...");
    	}
    	
    	public void afterMethod(){
    		System.out.println("卖酒之后...");
    	}
    	
    	public Object getTarget() {
    		return target;
    	}
    
    	public void setTarget(Object target) {
    		this.target = target;
    	}
    }

Test:

    // 产生一个被代理对象
    WineFactory wf = new WineFactoryImpl();
    // 将被代理对象交给InvocationHandler
    WineFactoryInvocationHandler wfih = new WineFactoryInvocationHandler();
    wfih.setTarget(wf);
    // 根据被代理对象产生一个代理
    WineFactory wfp = (WineFactory)Proxy.newProxyInstance(wf.getClass().getClassLoader(), wf.getClass().getInterfaces(), wfih);
    wfp.sell();

In addition to JDK dynamic agent, there is also a cglib dynamic agent. For details, please refer to the article (for this article): http://www.cnblogs.com/jqyp/archive/2010/08/20/1805041.html

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>