Everyone is more familiar with the proxy pattern in Java. The proxy mode can be divided into static proxy and dynamic proxy. Below we will analyze the static proxy and dynamic proxy through Demo.
We first implement a calculator interface class and implementation class, the specific code is as follows:
calculator interface class
public interface Calculator {
public int add(int x,int y);
}
Implementation class
public class CalculatorImpl implements Calculator {
@Override
public int add(int x, int y) {
return x+y;
}
}
static proxy
Let's first implement it through the static proxy mode:
public class StaticProxy {
private Calculator cal;
public StaticProxy(Calculator cal){
this.cal = cal;
}
public int add(int x,int y){
int result = cal.add(x, y);
return result;
}
}
In the above code, we complete the addition by calling the implementation class that actually implements the add method in StaticProxy. This method is intuitive and convenient, but if we have many classes that need to implement proxies, then we have to have one class and one proxy method. The above method Obviously not the best option. At this time, we can solve this problem well through the dynamic proxy method.
Dynamic proxy
We first write the Loghandler class to implement the InvocationHandler interface
public class Loghandler implements InvocationHandler {
Object obj;
Loghandler(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
doBefore();
Object o = method.invoke(obj, args);
doAfter();
return o;
}
public void doBefore(){
System.out.println("Invoke before.......");
}
public void doAfter(){
System.out.println("Invoke after........");
}
}
call Loghandler
Calculator cal = new CalculatorImpl();
Loghandler lh = new Loghandler(cal);
Calculator proxy = (Calculator)Proxy.newProxyInstance(cal.getClass().getClassLoader(),
cal.getClass().getInterfaces(), lh);
System.out.println(proxy.add(1, 3));
The method of creating a proxy through Proxy.newProxyInstance can create proxy classes for different proxy classes. We only need to implement the same proxy once to create proxy classes for multiple proxy classes.