浅谈静态代理和动态代理
2009-09-20 10:26
531 查看
1.静态代理,耦合增加,改动较大。
登录接口
用户登录
静态实现
静态测试
2.动态代理,耦合减小,代码改动小
动态代理实现
动态代理测试
登录接口
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(); }
相关文章推荐
- 浅谈Java代理(jdk静态代理、动态代理和cglib动态代理)
- 动态代理与静态代理之略见
- JDK的动态(静态)代理机制(转载并整理修改)
- Java 静态代理和动态代理
- 设计模式- 代理模式 (静态代理 和 动态代理)
- Java 静态代理与动态代理
- Java中三种代理方式—— 静态代理与两种动态代理的实现机制
- Java中静态代理和动态代理介绍
- 【java项目实战】代理模式(Proxy Pattern),静态代理 VS 动态代理
- 浅谈springAOP和动态代理
- java静态代理与动态代理简介(7)
- java 设计模式之四-代理模式 java静态代理和动态代理
- 静态代理和动态代理的再学习
- Java设计模式学习06——静态代理与动态代理
- 静态代理模式、动态代理模式(实现、对比)
- 静态代理,jdk动态代理和cjlib动态代理
- 【Java学习】静态代理与动态代理
- 静态代理、JDK与CGLIB动态代理
- Java静态代理和动态代理
- spring aop proxy 静态代理和动态代理