看名字就知道是干嘛的了。
代理模式 Proxy
看名字就能开解了。就是A可以访问B不能访问C,B能访问C,所以B把A的请求给C,把C的响应给A,顺便加点广告什么的,跳墙、VPN之类的都是如此。
问题:
You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.
意图:
- Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
- Wrap a complicated subsystem with a simpler interface
代码
例:跳墙,比如我能访问youtube,并开了个服务器为http://www.proxy.com/,后面加上youtube的地址就去访问youtube并返回
代码1:HTTP接口,实际上就一个方法
public interface HTTP {
public String visit(String url);
}
//以及一个具体的服务器
public class Server implements HTTP {
@Override
public String visit(String url) {
return "您正在访问页面" + url;
}
}
代码二:具体的服务器,国内的线路,与国外的线路,均可访问,但使用国内线路访问某些网站的时候会遭到河蟹。
public class ChinaServer implements HTTP{
@Override
public String visit(String url) {
if(url.startsWith("http://www.youtube.com/")){
return "被河蟹了";
}
return new Server().visit(url);
}
}
public class ProxyServer implements HTTP {
@Override
public String visit(String url) {
System.out.println("正在使用代理:www.proxy.com");
return new Server().visit(url);
}
}
代码三:客户端使用
public static void main(String[] args){
//普通用户,只能连接到带河蟹功能的ChinaServer
HTTP http = new ChinaServer();
System.out.println(http.visit("http://www.qq.com/abc"));
System.out.println(http.visit("http://www.youtube.com/video/1"));
//代理用户
http =new ProxyServer();
System.out.println(http.visit("http://www.qq.com/abc"));
System.out.println(http.visit("http://www.youtube.com/video/1"));
}
小结
代理模式 Proxy
- 使用频率:
中
代理模式在实际应用中还是挺多的,特别是多部件的项目,很多的奇葩规划设定导致很多部件不能去接使用很多功能,要一层层代理。
- 利弊影响:
中
规划的层级太多,不止是影响性能,而且也有很多不爽。