代理模式的主要目的是用来控制对对象的访问。用户不直接操作对象,而是通过代理来访问对象,这样代理可以在对象被访问的时候执行一些逻辑,过滤不合理的请求。下面是代理模式的UML
所以这其实是一个非常简单的模式,下面上一个简单的例子:
interface SomeBean {
void doSomething(String something) throws Exception;
}
class SomeBeanImpl implements SomeBean {
public void doSomething(String something) {
// Add business logic here
System.out.println("SomeBean is working on " + something);
}
}
class SomeBeanProxy implements SomeBean {
SomeBean someBean;
public SomeBeanProxy(SomeBean someBean) {
this.someBean = someBean;
}
public void doSomething(String something) throws Exception {
if (something.toLowerCase().contains("illegal")) {
throw new Exception("Reject doing illegal thing");
}
someBean.doSomething(something);
}
}
class SomeBeanFactory {
public static SomeBean getNewBean() {
return new SomeBeanProxy(new SomeBeanImpl());
}
}
public class TestProxyMode {
public static void main(String ...args) {
SomeBean someBean = SomeBeanFactory.getNewBean();
try {
someBean.doSomething("Homework");
someBean.doSomething("Illegal thing");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
这样不合法的请求就被代理给拒绝了。JDK中一些类的设计就使用了代理模式,比如说动态代理,RMI……