Proxy Pattern

Proxy Pattern


Mục đích của Proxy pattern là cung cấp một cơ chế đại diện cho một đối tượng khác để điều khiển truy cập đến đối tượng nó.  Giả sử chúng ta có một lớp có thể thực hiện một số lệnh trong hệ thống và chúng ta muốn chuyển chương trình này cho một ứng dụng khác. Điều này có thể gây ra một số rắc rối vì ứng dụng thứ ba này có thể ra lệnh xóa file hệ thống hay thay đỏi các thiết lập mà bạn không mong muốn. Proxy pattern giúp giải quyết vấn đề này.

1. Proxy Design Pattern – Main Class
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.");
 }

}

2. Proxy Design Pattern – Proxy Class

Giả sử chúng ta chỉ cho phép admin có toàn quyền truy cập đến lớp CommandExecutorImpl. Những user khác bị giới hạn sử dụng một số lệnh
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);
   }
  }
 }
}

3. Proxy Design Pattern Client Program
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());
  }
  
 }
}

Kết quả hiển thị chương trình
'ls -ltr' command executed.
Exception Message::rm command is not allowed for non-admin users.




  



No comments :

Post a Comment