Java proxy design pattern

Dictionary meaning of proxy: the authority to represent someone else.

Java proxy design pattern comes under the structural design pattern category. In proxy design pattern we use a surrogate or placeholder to control the access of original object.

Main advantage of java proxy design pattern is that it provides the protection to the original object from the outside world by providing the controlled access of original object.

Let’s understand the proxy design pattern with below example. We have OperationsPerformed interface with view and edit operations. Now we want that a user with ADMIN role only can do both view and edit operations, other users can only perform view operations. We are going to implement this with the proxy design pattern.

Example

OperationsPerformed.java

package com.w3spoint;
 
public interface OperationsPerformed {
	public void view();
	public void edit();
}

RealOperationsPerformed.java

package com.w3spoint;
 
public class RealOperationsPerformed implements OperationsPerformed {
	@Override
	public void view() {
		System.out.println("Performing view operation.");
	}
 
	@Override
	public void edit() {
		System.out.println("Performing edit operation.");
	}
}

ProxyOperationsPerformed.java

package com.w3spoint;
 
public class ProxyOperationsPerformed implements OperationsPerformed {
	private String userName;
	private RealOperationsPerformed  realOperationsPerformed; 
 
	public ProxyOperationsPerformed(String userName){
		this.userName = userName;
	}
 
	@Override
	public void view() {
	  if (getRole(userName).equals("ADMIN") || 
				getRole(userName).equals("USER")) {  
			realOperationsPerformed = new RealOperationsPerformed();  
			realOperationsPerformed.view();  
          }   
          else {  
            System.out.println("You can not view this record.");  
          }   
	}
 
	@Override
	public void edit() {
		if (getRole(userName).equals("ADMIN")) {  
			realOperationsPerformed = new RealOperationsPerformed();  
			realOperationsPerformed.edit();  
                }   
                else {  
                     System.out.println("You can not edit this record.");  
                }  
	}
 
	public String getRole(String userName) {  
            //Get user role by username
            return "ADMIN";  
        }  
}

ProxyPatternTest.java

package com.w3spoint;
 
public class ProxyPatternTest {
	public static void main(String args[]){
		OperationsPerformed operationsPerformed = new ProxyOperationsPerformed("jai");  
		operationsPerformed.view();
		operationsPerformed.edit();
	}
}

Output

Performing view operation.
Performing edit operation.
Please follow and like us:
Content Protection by DMCA.com