動態代理與靜態代理的區別。
靜態代理這個模式本身有個大問題,如果類方法數量越來越多的時候,代理類的代碼量是十分龐大的。所以引入動態代理來解決此類問題。
接口:
/**
* @author liuh
* @date 2018年5月28日 上午10:15:40
*/
public interface IUser {
// 查詢賬戶
public void queryAccount();
}
接口實現:
/**
* @author liuh
* @date 2018年5月28日 上午10:16:12
*/
public class UserImpl implements IUser {
@Override
public void queryAccount() {
System.out.println("查看賬戶...");
}
}
- 靜態代理:
/**
* @author liuh
* @date 2018年5月28日 上午10:16:47
*/
public class UserProxy implements IUser {
private IUser iUser;
public UserProxy(IUser iUser) {
this.iUser = iUser;
}
@Override
public void queryAccount() {
// TODO Auto-generated method stub
System.out.println("查看賬戶前--先登陸賬戶");
iUser.queryAccount();
}
public static void main(String[] args) {
IUser co = new UserImpl();
UserProxy coProxy = new UserProxy(co);
coProxy.queryAccount();
}
}
- 動態代理 有實現類:
/**
* @note 接口實現類 動態代理
* @author liuh
* @date 2018年5月28日 上午10:16:47
*/
public class UserProxy implements InvocationHandler {
private Object target;
public Object bind(Object target) {
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
// TODO Auto-generated method stub
System.out.println("預處理操作——————");
// 調用真正的業務方法
result = method.invoke(target, args);
System.out.println("調用後處理——————");
return result;
}
public static void main(String[] args) {
IUser iUser=(IUser)new UserProxy().bind(new UserImpl());
iUser.queryAccount();
}
}
- 動態代理 無實現類
/**
* @note 接口無實現類 動態代理
* @author liuh
* @date 2018年5月28日 上午10:16:47
*/
public class UserProxy implements InvocationHandler {
public Object bind(Class<?> target) {
return Proxy.newProxyInstance(target.getClassLoader(), new Class[] { target }, this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
// TODO Auto-generated method stub
System.out.println("預處理操作——————");
// 接口的抽象方法實現
if(method.getName().equals("queryAccount")) {
result = run(method,args);
}
System.out.println("調用後處理——————");
return result;
}
public Object run(Method method, Object[] args) {
// TODO
System.out.println("查看賬戶...");
return null;
}
public static void main(String[] args) {
// 通過此語句得到動態生成 的class 文件
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
IUser iUser = (IUser) new UserProxy().bind(IUser.class);
iUser.queryAccount();
}
}