Proxy pattern
- 정의
- 프록시 패턴은 어떤 다른 객체로 접근하는 것을 통제하기 위해서 그 객체의 대리자의 역할을 하는 객체를 제공하는 패턴
- 프록시 패턴 적용예시
- 예를 들어, 우리가 시스템 명령어를 실행하는 객체를 갖고 있을 때 우리가 그 객체를 사용하는 것이라면 괜찮지만, 만약 그 객체를 클라이언트에게 제공하려고 한다면 클라이언트 프로그램이 우리가 원치 않는 파일을 삭제하거나 설정을 변경하는 등의 명령을 내릴 수 있기 때문에 심각한 문제를 초래할 수 있다.
- 프록시 패턴은 클라이언트에게 접근에 대한 컨트롤을 제공하여 위와 같은 문제를 해결
- 상품데이터를 저장하는 클래스와 해당 데이터를 가지고 편집하는 프록시 클래스를 따로두어 권한 및 벨리데이션 체크
적용 예시 코드
1. CommandExecutorImpl 객체 : 파라미터로 받은 명령어를 그대로 수행
protocol CommandExecutor {
func runCommand(String)
}
class CommandExecutorImpl: CommandExecutor {
func runCommand(command: String ) {
//some heavy implementation
Runtime.getRuntime().exec(command)
print(command + "command executed.")
}
}
- 클라이언트가 CommandExecutorImpl 객체를 통해 명령어를 실행하는 경우 권한체크없이 원치 않는 파일 삭제나 설정 변경 등에 문제가 발생할 가능성이 있다.
2. CommandExecutorProxy 객체
class CommandExecutorProxy: CommandExecutor {
private var isAdmin : Bool
private var executor : CommandExecutor
convenience init(user : String, pwd: String){
if("ReadyKim" == user) && correct_pwd == pwd) {
self.isAdmin = true
} else {
self.isAdmin = false
}
self.executor = CommandExecutorImpl()
}
override func runCommand(cmd: Strirng) {
if(isAdmin){
executor.runCommand(cmd)
}else{
if(cmd.contains("rm")){
print("rm command is not allowed for non-admin users.")
}else{
executor.runCommand(cmd)
}
}
}
}
- 프록시 객체를 두어 관리자(Admin) 계정이 아닐 경우에는 rm 이라는 명령어에 대해 수행하지 못하도록 구현할 수 있다.
- 프록시 패턴은 클라이언트에게 접근에 대한 컨트롤을 제공
참고
https://ko.wikipedia.org/wiki/%ED%94%84%EB%A1%9D%EC%8B%9C_%ED%8C%A8%ED%84%B4
https://readystory.tistory.com/132?category=822867
'Object-Oriented Programming > Design Pattern' 카테고리의 다른 글
Composite Pattern, 컴포지트 패턴 (0) | 2022.07.28 |
---|---|
Decorator Pattern, 데코레이터 패턴 (0) | 2022.07.19 |
Template method pattern, 템플릿 메소드 패턴 (0) | 2022.05.16 |
Abstract Factory Pattern, 추상 팩토리 패턴 (0) | 2022.05.11 |
Factory Method Pattern, 팩토리 메소드 패턴 (0) | 2022.05.09 |