您的位置:首页 > 其它

浅谈静态代理和动态代理

2009-09-20 10:26 531 查看
1.静态代理,耦合增加,改动较大。

登录接口

public class CustomerLoginAction implements LoginAction {
//执行验证操作
public void execute() throws SQLException, LoginException  {
}
}


用户登录

import java.sql.SQLException;

public interface  LoginAction  {

public void execute()throws SQLException, LoginException;

}


静态实现

public class ProxyCustomerLoginAction implements LoginAction {

private LoginAction  customerLogin ;

public ProxyCustomerLoginAction(LoginAction customerLogin){
this.customerLogin = customerLogin;
}
public void execute() throws SQLException, LoginException{
System.out.println("begin the login validate");
customerLogin.execute();
System.out.println("end the login validate");
}

}


静态测试

public static void main(String[] args) {
CustomerLoginAction customerLoginAction = new CustomerLoginAction();
LoginAction pAction = new ProxyCustomerLoginAction(customerLoginAction);
}


2.动态代理,耦合减小,代码改动小

动态代理实现

public class DynaProxyCustomerLoginHandler implements InvocationHandler {

private Object realclass;

public Object binding(Object realclass) {
this.realclass = realclass;
//返回一个代理类的实例
return Proxy.newProxyInstance(realclass.getClass().getClassLoader(),
realclass.getClass().getInterfaces(), this);
}

//在被代理类的实例前后增加功能
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object obj = null;
//如果被代理类方法的名字包含指定的字符串"execute",则在被代理类方法执行的前后增加新的功能,
//否则直接执行被代理类的方法,而不增加新的功能。
if (method.getName().contains("execute")) {
System.out.println("begin the login validate");
try {
//执行被代理类的方法
obj = method.invoke(realclass, args);
} catch (Exception e) {
}
System.out.println("end the login validate");
return obj;
} else {
obj = method.invoke(realclass, args);
return obj;
}

}

}


动态代理测试

public static void main(String[] args) {
DynaProxyCustomerLoginHandler loginHandler = new DynaProxyCustomerLoginHandler();
CustomerLoginAction customerLoginAction = new CustomerLoginAction();
LoginAction loginAction = (LoginAction)loginHandler.binding(customerLoginAction);
loginAction.execute();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: