Proxy Design Pattern Example in Java
In this example, We will show you about, How to Create Proxy Design Pattern Example in Java. The example were tested with environment and output has been shared in the same post.
What is the Proxy Design Pattern ?
#1 Server.java
package com.dineshkrish; public interface Server { public String getResponse(); }
#2 ApplicationServer.java
package com.dineshkrish; public class ApplicationServer implements Server { private String request; public ApplicationServer(String request) { this.request = request; } @Override public String getResponse() { return processRequest(request); } public String processRequest(String request) { System.out.println("Server Processing your Request of ("+request+")"); String response = ""; if(request.equals("https://idineshkrishnan.com/page1")) { response = "Showing the Page 1 Content"; } else if(request.equals("https://idineshkrishnan.com/page2")) { response = "Showing the Page 2 Content"; } else if(request.equals("https://idineshkrishnan.com/page3")) { response = "Showing the Page 3 Content"; } else { response = "Page Not Found!!!"; } return response; } }
#3 ProxyServer.java
package com.dineshkrish; public class ProxyServer implements Server { private ApplicationServer applicationServer; private String request; public ProxyServer(String request) { this.request = request; } @Override public String getResponse() { if(applicationServer == null) { applicationServer = new ApplicationServer(request); } return applicationServer.getResponse(); } }
#4 Client.java
package com.dineshkrish; public class Client { public static void main(String[] args) { String requst1 = "https://idineshkrishnan.com/page1"; String requst2 = "https://idineshkrishnan.com/page2"; String requst3 = "https://idineshkrishnan.com/page3"; String requst4 = "https://idineshkrishnan.com/page4"; Server server1 = new ProxyServer(requst1); System.out.println(server1.getResponse()); Server server2 = new ProxyServer(requst2); System.out.println(server2.getResponse()); Server server3 = new ProxyServer(requst3); System.out.println(server3.getResponse()); Server server4 = new ProxyServer(requst4); System.out.println(server4.getResponse()); } }
Output
Server Processing your Request of (https://idineshkrishnan.com/page1)
Showing the Page 1 Content
Server Processing your Request of (https://idineshkrishnan.com/page2)
Showing the Page 2 Content
Server Processing your Request of (https://idineshkrishnan.com/page3)
Showing the Page 3 Content
Server Processing your Request of (https://idineshkrishnan.com/page4)
Page Not Found!!!
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet