请基于 Proxy 模式编写一个访问控制程序,禁止用户访问对象的某些字段,其主程 序的关键代码如下: public class ProxyClient { public static void main(String[] args) { ... proxy = ...("...","...","..."); ...(proxy.readProperty("..")); ... }
时间: 2023-05-14 08:06:37 浏览: 100
好的,基于 Proxy 模式编写一个访问控制程序,禁止用户访问对象的某些字段的代码如下:
public interface ISubject {
void readProperty(String property);
}
public class RealSubject implements ISubject {
private String sensitiveProperty;
public RealSubject(String sensitiveProperty) {
this.sensitiveProperty = sensitiveProperty;
}
@Override
public void readProperty(String property) {
if (property.equals(sensitiveProperty)) {
throw new RuntimeException("Access denied to sensitive property");
} else {
System.out.println("Access granted to property: " + property);
}
}
}
public class Proxy implements ISubject {
private RealSubject realSubject;
public Proxy(String sensitiveProperty) {
this.realSubject = new RealSubject(sensitiveProperty);
}
@Override
public void readProperty(String property) {
realSubject.readProperty(property);
}
}
public class ProxyClient {
public static void main(String[] args) {
Proxy proxy = new Proxy("sensitiveProperty");
proxy.readProperty("publicProperty");
proxy.readProperty("sensitiveProperty");
}
}
在这个例子中,我们创建了一个 RealSubject 类来表示一个具有敏感属性的对象。然后,我们创建了一个 Proxy 类来代理 RealSubject 对象,并在其中实现了访问控制逻辑。最后,我们在主程序中使用 Proxy 对象来访问 RealSubject 对象的属性,并测试了访问控制的效果。
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)