结构设计模式 - 代理设计模式

 

结构设计模式 - 代理设计模式

 

代理设计模式是结构设计模式之一,在我看来是最简单的模式之一。

 

 

目录[ 隐藏 ]

代理设计模式

根据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 {
                //some heavy implementation
		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中代理设计模式的全部内容。

 

转载来源:https://www.journaldev.com/1572/proxy-design-pattern

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值