プロキシ設計パターン

プロキシデザインパターンは、構造デザインパターンの一つであり、私の意見では理解しやすいパターンの一つです。

プロキシデザインパターン

GoFによるProxyデザインパターンの意図は、他のオブジェクトの代理またはプレースホルダを提供し、アクセスを制御することです。その定義自体は非常に明確であり、Proxyデザインパターンは機能の制御されたアクセスを提供したい場合に使用されます。たとえば、システム上でいくつかのコマンドを実行できるクラスがあるとします。これを使用している場合は問題ありませんが、このプログラムをクライアントアプリケーションに提供したい場合、クライアントプログラムがシステムファイルを削除したり設定を変更したりする可能性があり、深刻な問題が発生するかもしれません。ここで、プログラムの制御されたアクセスを提供するためにProxyクラスを作成することができます。

プロキシデザインパターン – メインクラス

私たちはJavaをインターフェースの観点でコーディングしているので、ここに私たちのインターフェースとその実装クラスがあります。CommandExecutor.java

package com.scdev.design.proxy;

public interface CommandExecutor {

	public void runCommand(String cmd) throws Exception;
}

CommandExecutorImpl.javaを日本語で完全に言い換える。オプションは1つだけ必要です。

package com.scdev.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.scdev.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);
			}
		}
	}

}

プロキシデザインパターンのクライアントプログラム

Proxyパターンのテストを行うProxyPatternTest.java

package com.scdev.design.test;

import com.scdev.design.proxy.CommandExecutor;
import com.scdev.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におけるプロキシデザインパターンに関する説明です。

コメントを残す 0

Your email address will not be published. Required fields are marked *