A Structural Design Pattern which controls the access to a heavy resource extensive object by providing surrogate object that has similar method.
Intention
- Can be used to control the access to an Object
- Deters the creation of heavy object until it required completely
- Reduces the number of actual object calls providing a surrogate object
Subject - The common interface that implements both real and proxy objects.
Real Object - The actual object that client needs to work with.
Proxy - The object client is provided to represent the actual object hiding the complexity.
Client - The user who needs to interact with the Subject.
Subject
public interface Loader {
public void getFile();
}
Real Object
public class FileLoader implements Loader {
@Override
public void getFile(){
System.out.println("Accessing the file");
}
}
Proxy Object
public class ProxyFileLoader implements Loader {
private FileLoader fileLoader;
private boolean isAutorized;
public ProxyFileLoader(String userName, String password) {
if ("userA".equalsIgnoreCase(userName)
&& "passwordA".equalsIgnoreCase(password)) {
setAutorized(true);
}
fileLoader = new FileLoader();
}
@Override
public void getFile() {
if (isAutorized) {
fileLoader.getFile();
}
else {
System.out.println("Cannot access the file.");
}
}
public boolean isAutorized() {
return isAutorized;
}
public void setAutorized(boolean isAutorized) {
this.isAutorized = isAutorized;
}
}
Client
public class Client {
public static void main(String[] args) {
Loader loader = new ProxyFileLoader("userA", "passwordA");
loader.getFile(); // Output: Accessing the file
Loader loaderWithIncorrectCredintials = new ProxyFileLoader(
"wrongUser", "wrongPassword");
loaderWithIncorrectCredintials.getFile(); // Output: Cannot access the file.
}
}
No comments:
Post a Comment