代理模式 Proxy Pattern
为其他对象提供一种代理以控制对这个对象的访问。
在部署Web应用时,通常都会使用Nginx作为反向代理,这种模式下,在浏览器看来把HTTP请求发给Nginx和Tomcat得到的结果是相同的。
UML图:
代码:
public interface WebServer {
String getHttp();
}
public class Tomcat implements WebServer {
@Override
public String getHttp() {
return "GET /index HTTP/1.1";
}
}
public class Nginx implements WebServer {
private Tomcat tomcat;
public Nginx() {
}
@Override
public String getHttp() {
if(tomcat == null) {
tomcat = new Tomcat();
}
return tomcat.getHttp();
}
}
客户端:
public class Client {
public static void main(String[] args) {
Nginx nginx = new Nginx();
System.out.println(nginx.getHttp());
}
}