0002

动态代理:


[img]http://dl.iteye.com/upload/attachment/0072/2863/4bf62c6d-d2b3-3cd5-9aa8-6b282547231b.jpg[/img]


package com.test.dynamicproxy;
/**
* 抽象角色
* @author Administrator
*
*/
public interface Business {
public String goCity();
}

----------------------------------
package com.test.dynamicproxy;

/***
* 真实角色
* @author Administrator
*
*/
public class BusinessImpl implements Business {

@Override
public String goCity() {
System.out.println("去南京 ,怎么去。。。。。。");
return "businessImpl 真实角色的返回值。。。。。。。。。。。。。。。。。。。。。";
}

}


--------------------------------------
package com.test.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class BusinessImplProxy implements InvocationHandler {

private Object obj;

public BusinessImplProxy() {
}

public BusinessImplProxy(Object obj) {
this.obj = obj;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
doBefore();
result = method.invoke(obj, args);
doAfter();
return result;
}

public static Object getRealFactory(Object obj) {

return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
.getClass().getInterfaces(), new BusinessImplProxy(obj));
}

public void doBefore(){
System.out.println("dobefore....................");
}

public void doAfter(){
System.out.println("doAfter....................");
}

}
-----------------------------------------------------
package com.test.dynamicproxy;

import org.junit.Test;

import junit.framework.TestCase;

public class JunitTest extends TestCase {

@Test
public void testDynamicProxy(){
BusinessImpl b = new BusinessImpl();
Business business = (Business)BusinessImplProxy.getRealFactory(b);
String tmp = business.goCity();

System.out.println("result:"+tmp+"");



}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值