代理設計模式

代理設計模式是結構設計模式之一,在我看來是最簡單易懂的模式之一。

代理設計模式

代理設計模式的意圖根據 GoF 是:為另一個對象提供代理或佔位符,以控制對它的訪問。 定義本身非常清晰,代理設計模式用於當我們想要提供功能的受控訪問時。假設我們有一個能夠在系統上運行某些命令的類。現在如果我們在使用它,這很好,但如果我們想要將此程序提供給客戶應用程序,它可能會有嚴重問題,因為客戶程序可能會發出刪除一些系統文件或更改一些不希望更改的設置的命令。在這種情況下,可以創建一個代理類來提供程序的受控訪問。

代理設計模式 – 主類

由於我們用 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 {
                //一些重要的實作
		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 套件使用了代理模式。這就是關於 Java 中代理設計模式的所有內容。

Source:
https://www.digitalocean.com/community/tutorials/proxy-design-pattern