目前学习阶段,有问题请帮忙指出,谢谢
代理模式有三种:
- 静态代理模式
- jdk动态代理模式
- cglib动态代理模式
关于为什么使用代理模式,代理模式的作用,在网上的说明已经很多了
参考https://www.javaworld.com/article/2074068/take-control-with-the-proxy-design-pattern.html
本文主要是深入了解一下Jdk代理和Cglib代理的实现原理
静态代理比较好理解,先展示一下代码,下一篇再深入了解一下Jdk动态代理的具体实现
静态代理
package com.learn.design.pattern.proxy;
import lombok.AllArgsConstructor;
/**
* 静态代理模式
* @author lizj
* Date: 2019/6/13
*/
public interface StaticProxy {
/**
* 定义方法
*/
void doSomething();
/**
* 实现对象
*/
class AchieveObject implements StaticProxy{
@Override
public void doSomething() {
System.out.println("Achieve StaticProxy");
}
}
/**
* 代理对象
*/
@AllArgsConstructor
class ProxyObject implements StaticProxy{
private AchieveObject achieveObject;
@Override
public void doSomething() {
System.out.println("Achieve StaticProxy before");
achieveObject.doSomething();
System.out.println("Achieve StaticProxy after");
}
}
}
jdk动态代理
package com.learn.design.pattern.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* jdk动态代理模式
* @author lizj
* Date: 2019/6/13
*/
public interface JdkProxy {
/**
* 定义方法
*/
void doSomething();
/**
* 实现对象
*/
class AchieveObject implements JdkProxy{
@Override
public void doSomething() {
System.out.println("Achieve JdkProxy");
}
}
/**
* jdk动态代理对象
*/
class ProxyObject implements InvocationHandler {
private Object targetObj;
public Object newProxyObject(Object targetObj){
this.targetObj = targetObj;
return Proxy.newProxyInstance(targetObj.getClass().getClassLoader(), targetObj.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Achieve JdkProxy before");
Object obj = method.invoke(targetObj, args);
System.out.println("Achieve JdkProxy after");
return obj;
}
}
}
cglib动态代理:
package com.learn.design.pattern.proxy;
/**
* 实现对象
* @author lizj
* Date: 2019/6/13
*/
public class CglibObject {
public void doSomething(){
System.out.println("do something");
}
}
package com.learn.design.pattern.proxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* cglib代理
* @author lizj
* Date: 2019/6/13
*/
public class CglibProxy implements MethodInterceptor{
private Object targetObject;
public Object newProxyObject(Object targetObject){
this.targetObject = targetObject;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(targetObject.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("do something before");
Object result = methodProxy.invoke(targetObject, objects);
System.out.println("do something after");
return result;
}
}
网友评论