Proxy Pattern - Structural pattern
"It is used to provide the control for accessing the original object".
Proxy pattern is to provide a Surrogate or Placeholder for an object to control its references.
Subject: Interface implemented by the RealSubject and representing its services.
It is also implemented by Proxy.
Proxy: Controls access to the RealSubject and may be responsible for its creation and deletion.
RealSubject.
package designpattern.proxy;
public interface AdminRightAccess {
public void grantInternetAccess();
}
public class AdminProxy implements AdminRightAccess {
private String empId;
private AdminAccess adminAccess;
public AdminProxy(String empId) {
this.empId = empId;
}
@Override
public void grantInternetAccess() {
if(getRole(empId)==1) {
adminAccess = new AdminAccess(empId);
adminAccess.grantInternetAccess();
} else {
System.out.println("Admin rights given to "+ empId);
}
}
public int getRole(String empId) {
// Check role from the database based on empId
// return 1; if employee is admin
return 1;
}
}
public class AdminAccess implements AdminRightAccess {
private String empId;
public AdminAccess(String empId) {
this.empId = empId;
}
@Override
public void grantInternetAccess() {
System.out.println("Admin service loaded and"
+ "rights given to "+ empId);
}
}
package designpattern.proxy;
public class ProxyPatternClient {
public static void main(String[] args) {
AdminRightAccess access = new AdminProxy("Michael");
access.grantInternetAccess();
}
}
Output: Admin service loaded andrights given to Michael
No comments:
Post a Comment