`
yjian84
  • 浏览: 40188 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

0002

阅读更多
动态代理:








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+"");



}

}



  • 描述: UML图
  • 大小: 69.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics