Spring中实现Proxy模式

Spring中使用Proxy模式很多,经典就是AOP中的代理了,但是这里想讨论的是我们在自己的代码中实现代理模式的问题。

在上一篇Spring实现factory模式中,我们需要使用Person里面的方法,但是type是程序运行的过程中才知道是多少,如果要使用Person接口需要在代码里面动态的判断到底使用哪种对象,这时候使用Factory模式就很难实现这种了。
撇开配置,我们最直接的想法是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public interface Handler{
int handler( int type);
}

public class Handler1 implements Handler{
int handler(int type){
return type +1;
}
}

public class Handler2 implements Handler{
int handler(int type){
return type +2;
}
}

public class TestHandler{
private Handler handler;

public void testhandler(){
int type = (int) random();
if(type == 0){
handler = new Handler1();
}else{
handler = new Handler2();
}
handler.handler(type);
}
}

这种代码使用Proxy模式是合适的。

Proxy模式[http://en.wikipedia.org/wiki/Proxy_pattern] :所谓的代理者是指一个类型可以作为其它东西的接口。
我们可以将PersonHandler 里面的person使用prox的方式来实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class HandlerProxy implements Handler{
int handler(int type){
int type = (int) random();
if(type == 0){
handler = new Handler1();
}else{
handler = new Handler2();
}
return handler.handler(type);
}
}

public class TestHandler{
private Handler handler = new HandlerProxy();

public void testhandler(){
int type = (int) random();

handler.handler(type);
}
}

这样在配时就可以采用如下配置

1
2
<bean id="handler1" class="Handler1" />
<bean id="handler2" class = "Handler2"/>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class HandlerProxy implements Handler{

@Autowired
private Handler handler1
@Autowired
private Handler handler2
int handler(int type){

int type = (int) random();
if(type == 0){
return handler1.handler(type);
}else{
return handler2.handler(type);
}

}
}