프록시 디자인 패턴
프록시 디자인 패턴은 구조 디자인 패턴 중 하나이며 제 생각에는 이해하기 가장 간단한 패턴 중 하나입니다.
프록시 디자인 패턴
프록시 디자인 패턴 - 메인 클래스
우리는 인터페이스 측면에서 Java를 코딩하므로 여기에 인터페이스와 해당 구현 클래스가 있습니다. CommandExecutor.java
package com.journaldev.design.proxy;
public interface CommandExecutor {
public void runCommand(String cmd) throws Exception;
}
CommandExecutorImpl.java
package com.journaldev.design.proxy;
import java.io.IOException;
public class CommandExecutorImpl implements CommandExecutor {
@Override
public void runCommand(String cmd) throws IOException {
//some heavy implementation
Runtime.getRuntime().exec(cmd);
System.out.println("'" + cmd + "' command executed.");
}
}
프록시 디자인 패턴 - 프록시 클래스
이제 관리자 사용자에게만 위 클래스에 대한 전체 액세스 권한을 제공하려고 합니다. 사용자가 관리자가 아닌 경우 제한된 명령만 허용됩니다. 다음은 매우 간단한 프록시 클래스 구현입니다. CommandExecutorProxy.java
package com.journaldev.design.proxy;
public class CommandExecutorProxy implements CommandExecutor {
private boolean isAdmin;
private CommandExecutor executor;
public CommandExecutorProxy(String user, String pwd){
if("Pankaj".equals(user) && "J@urnalD$v".equals(pwd)) isAdmin=true;
executor = new CommandExecutorImpl();
}
@Override
public void runCommand(String cmd) throws Exception {
if(isAdmin){
executor.runCommand(cmd);
}else{
if(cmd.trim().startsWith("rm")){
throw new Exception("rm command is not allowed for non-admin users.");
}else{
executor.runCommand(cmd);
}
}
}
}
프록시 디자인 패턴 클라이언트 프로그램
ProxyPatternTest.java
package com.journaldev.design.test;
import com.journaldev.design.proxy.CommandExecutor;
import com.journaldev.design.proxy.CommandExecutorProxy;
public class ProxyPatternTest {
public static void main(String[] args){
CommandExecutor executor = new CommandExecutorProxy("Pankaj", "wrong_pwd");
try {
executor.runCommand("ls -ltr");
executor.runCommand(" rm -rf abc.pdf");
} catch (Exception e) {
System.out.println("Exception Message::"+e.getMessage());
}
}
}
위의 프록시 디자인 패턴 예제 프로그램의 출력은 다음과 같습니다.
'ls -ltr' command executed.
Exception Message::rm command is not allowed for non-admin users.
프록시 디자인 패턴의 일반적인 용도는 액세스를 제어하거나 더 나은 성능을 위해 래퍼 구현을 제공하는 것입니다. Java RMI 패키지는 프록시 패턴을 사용합니다. 이것이 자바의 프록시 디자인 패턴의 전부입니다.