代码拉取完成,页面将自动刷新
代理模式是一种结构型设计模式,让你能够提供对象的替代品或其占位符。
代理控制着对于原对象的访问,并允许在将请求提交给对象前后进行一些处理。
优点:
缺点:
后续讲到对应的模式时再写
以上为静态代理,
还有动态代理的实现方式:
接口:
public interface CommandExecutor {
void runCommand(String cmd) throws Exception;
}
被代理类(原来的实现类):
public class CommandExecutorImpl implements CommandExecutor{
@Override
public void runCommand(String cmd) throws Exception {
// ... (执行对应操作)
System.out.println("'" + cmd + "' command executed.");
}
}
代理类:
public class CommandExecutorProxy implements CommandExecutor{
/**
* 指向原服务的引用
*/
private CommandExecutor executor;
private boolean isAdmin;
public CommandExecutorProxy(String user, String pwd){
if("admin".equals(user) && "abcABC123!@#".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);
}
}
}
}
测试代码
public class ProxyTest {
@Test
public void test() throws Exception {
CommandExecutor executor = new CommandExecutorProxy("admin", "abcABC123!@#");
executor.runCommand("ls");
executor.runCommand("rm -rf *");
}
@Test
public void testException() {
Exception exception = Assertions.assertThrows(Exception.class, () -> {
CommandExecutor executor = new CommandExecutorProxy("admin", "123456");
executor.runCommand("ls");
executor.runCommand("rm -rf *");
});
Assertions.assertEquals("rm command is not allowed for non-admin users.", exception.getMessage());
}
}
Proxy 提供用于创建动态代理类和实例的静态方法
...
CDI 托管 bean 实例本质上是一个自动生成类的可序列化代理实例,它扩展了原始支持 bean 类并通过公共方法将所有公共方法进一步委托给实际实例
public CDIManagedBeanProxy extends ActualManagedBean implements Serializable { public String getSomeProperty() { ActualManagedBean instance = CDI.resolveItSomehow(); return instance.getSomeProperty(); } public void setSomeProperty(String someProperty) { ActualManagedBean instance = CDI.resolveItSomehow(); instance.setSomeProperty(someProperty); } }
Spring AOP (JDK 动态代理和 cglib 动态代理)
利用职责链模式和动态代理模式来实现 MyBatis Plugin
这个等后续讲到职责链再写
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。