代理模式和委托模式
程序员文章站
2022-06-09 22:00:58
...
1. 静态代理
public class DefaultProcess implements IProcess{
@Override
public void process() {
System.out.println("DefaultProcess!");
}
}
public class ProxyProcess implements IProcess{
private IProcess process;
public ProxyProcess(IProcess process){
this.process = process;
}
@Override
public void process() {
process.process();
}
}
2. 动态代理
public class Handler implements InvocationHandler{
private Object target;//代理对象
public Handler(Object target){this.target = target;}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理方法执行前");
method.invoke(target,args);
System.out.println("代理方法执行后");
return proxy;
}
}
public class HandlerTest {
private IProcess process;
@Before
public void before() throws Exception {
process = new IProcess() {
@Override
public void process() {
System.out.println("DefaultProcess");
}
};
}
@After
public void after() throws Exception {}
/**
*
* Method: test(Process process)
*
*/
@Test
public void testTest() throws Exception {
//TODO: Test goes here...
}
/**
*
* Method: invoke(Object proxy, Method method, Object[] args)
*
*/
@Test
public void testInvoke() throws Exception {
Handler handler = new Handler(process);
IProcess p = (IProcess) Proxy.newProxyInstance(process.getClass().getClassLoader(),process.getClass().getInterfaces(), handler);
p.process();
}
}
上一篇: 二分求幂(一种快速幂运算的方法)
下一篇: 求字符串数组长度的一种方法