代理模式
- 静态代理
- 功能列表(接口)
- 原有功能,功能的实现
- 在不破坏原功能的情况下Enhance
- Test
- JDK 动态代理
- Cglib 代理模式
- Callback的MethodInterceptor
- test
静态代理
在不破坏原有功能的情况下,进行升级改造。
使用场景,通常在旧项目改造和升级中,不能或者没有条件在源码的基础上升级和改造
所以用代理模式是一个不错的选择。
功能列表(接口)
public interface IDoing {public String doFirst();public void doSecond();
}
原有功能,功能的实现
@Slf4j
public class DoingImpl implements IDoing {@Overridepublic String doFirst() {String me = "Hi there,this is Michael";return me;}@Overridepublic void doSecond() {log.info("let's started now");}
}
在不破坏原功能的情况下Enhance
public class DoingProxy implements IDoing {private IDoing idoing;DoingProxy(){this.idoing = new DoingImpl();}@Overridepublic String doFirst() {return idoing.doFirst().toUpperCase();}@Overridepublic void doSecond() {idoing.doSecond();}
}
Test
@Slf4j
public class TestProxy {public static void main(String[] args) {IDoing idoing = new DoingImpl();IDoing idoing = new DoingProxy();log.info(idoing.doFirst());idoing.doSecond();}
}
Hi there,this is Michael
HI THERE,THIS IS MICHAEL
let’s started now
JDK 动态代理
在静态代理的基础上改造
@Slf4j
public class TestProxy {public static void main(String[] args) {IDoing target = new DoingImpl();IDoing proxyIdoing = (IDoing) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {Object result = method.invoke(target, args);if (result!=null) {result = result.toString().toUpperCase();}return result;}} );String doFirst = proxyIdoing.doFirst();log.info(doFirst);proxyIdoing.doSecond();}
}
Cglib 代理模式
Callback的MethodInterceptor
public interface MethodInterceptor extends Callback
public class CglibProxyEnhancer implements MethodInterceptor {public DoingImpl getCglibCreator() {Enhancer enhancer = new Enhancer();enhancer.setSuperclass(DoingImpl.class);enhancer.setCallback(this);return (DoingImpl) enhancer.create();}@Overridepublic Object intercept(Object obj, Method method, Object[] args,MethodProxy proxy) throws Throwable {Object result = method.invoke(new DoingImpl(), args);if (result!=null) {result = result.toString().toUpperCase();}return result;}
}
test
@Slf4j
public class TestProxy {public static void main(String[] args) {CglibProxyEnhancer cglibProxyEnhancer = new CglibProxyEnhancer();DoingImpl proxyIdoing = cglibProxyEnhancer.getCglibCreator();String doFirst = proxyIdoing.doFirst();log.info(doFirst);proxyIdoing.doSecond();}
}