프록시 디자인 패턴은 구조적인 디자인 패턴 중 하나이며, 제일 쉽게 이해할 수 있는 패턴 중 하나라고 생각합니다.
프록시 디자인 패턴
GoF에 따르면 프록시 디자인 패턴의 의도는 다음과 같습니다: 다른 객체에 대한 대리자 또는 자리 표시자를 제공하여 접근을 제어합니다. 정의 자체가 매우 명확하며, 프록시 디자인 패턴은 기능에 대한 제어된 접근을 제공하고자 할 때 사용됩니다. 시스템에서 명령을 실행할 수 있는 클래스가 있다고 가정해 봅시다. 이 클래스를 사용하는 경우에는 괜찮지만, 이 프로그램을 클라이언트 애플리케이션에 제공하려는 경우, 클라이언트 프로그램이 시스템 파일을 삭제하거나 설정을 변경하는 등 원하지 않는 문제가 발생할 수 있습니다. 이럴 때 프록시 클래스를 생성하여 프로그램의 제어된 접근을 제공할 수 있습니다.
프록시 디자인 패턴 – 메인 클래스
자바에서는 인터페이스를 기반으로 코드를 작성하기 때문에, 여기에는 인터페이스와 그 구현 클래스가 있습니다. 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 {
//일부 중요한 구현
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 패키지는 프록시 패턴을 사용합니다. 이것이 자바에서의 프록시 디자인 패턴에 대한 모든 것입니다.
Source:
https://www.digitalocean.com/community/tutorials/proxy-design-pattern