标签:
package com.che.carcheck.ui.helper;
import com.che.carcheck.support.util.LogUtil;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 代理模式学习
*
* 作者:余天然 on 16/5/6 下午2:30
*/
public class ProxyStudy {
//使用场景
public static void main() {
//被代理类
UserImpl impl = new UserImpl("小明");
impl.login();
impl.updateInfo();
//静态代理
LogUtil.print("静态代理:开始");
UserStaticProxy staticProxy = new UserStaticProxy(impl);
staticProxy.login();
staticProxy.updateInfo();
//动态代理
LogUtil.print("动态代理:开始");
UserDynamicProxyFactory factory = new UserDynamicProxyFactory();
User dynamicProxy = (User) factory.createProxy(impl);
dynamicProxy.login();
dynamicProxy.updateInfo();
}
//接口
public interface User {
void login();
void updateInfo();
}
//被代理类
public static class UserImpl implements User {
private String name;
public UserImpl(String name) {
this.name = name;
}
@Override
public void login() {
LogUtil.print(this.name + "登录……");
}
@Override
public void updateInfo() {
LogUtil.print(this.name + "更新信息……");
}
}
//静态代理
public static class UserStaticProxy implements User {
private UserImpl countImpl;
public UserStaticProxy(UserImpl countImpl) {
this.countImpl = countImpl;
}
@Override
public void login() {
doBefore();
countImpl.login();
}
@Override
public void updateInfo() {
doBefore();
countImpl.updateInfo();
doAfter();
}
private void doBefore() {
LogUtil.print("静态代理:前置动作……");
}
private void doAfter() {
LogUtil.print("静态代理:后置动作……");
}
}
//JDK动态代理
public static class UserDynamicProxyFactory implements InvocationHandler {
private Object target;
//绑定委托对象并返回一个代理类
public Object createProxy(Object target) {
this.target = target;
//取得代理对象
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);//要绑定接口(这是一个缺陷,cglib弥补了这一缺陷)
}
//改变方法的调用逻辑
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
//执行方法
if (method.getName().equals("login")) {
doBefore();
result = method.invoke(target, args);
}
if (method.getName().equals("updateInfo")) {
doBefore();
result = method.invoke(target, args);
doAfter();
}
return result;
}
private void doBefore() {
LogUtil.print("动态代理:前置动作……");
}
private void doAfter() {
LogUtil.print("动态代理:后置动作……");
}
}
}
标签:
原文地址:http://blog.csdn.net/fisher0113/article/details/51331938