代理模式
结构型模式
访问次数: 19
代理模式为其他对象提供一种代理以控制对这个对象的访问。
视频教程
类图
classDiagram
class Subject {
<<interface>>
+request()
}
class RealSubject {
+request()
}
class Proxy {
-realSubject: RealSubject
+request()
}
Subject <|-- RealSubject
Subject <|-- Proxy
Proxy --> RealSubject
源代码示例
// 抽象主题
interface Subject {
void request();
}
// 真实主题
class RealSubject implements Subject {
@Override
public void request() {
System.out.println("RealSubject request");
}
}
// 代理类
class Proxy implements Subject {
private RealSubject realSubject;
@Override
public void request() {
if (realSubject == null) {
realSubject = new RealSubject();
}
// 前置处理
System.out.println("Proxy: Before request");
// 调用真实对象
realSubject.request();
// 后置处理
System.out.println("Proxy: After request");
}
}
# Python代码待添加
应用场景
当需要控制对对象的访问,或者在访问对象时添加额外的功能时。应用场景包括:
1)远程代理,为远程对象提供本地代理,隐藏网络通信的复杂性
2)虚拟代理,延迟创建昂贵的对象,直到真正需要时才创建
3)保护代理,控制对敏感对象的访问,提供权限验证
4)智能引用代理,在访问对象时添加额外的功能(如引用计数、懒加载)
5)缓存代理,为昂贵的操作提供缓存功能,提高系统性能
6)防火墙代理,在网络层控制对特定服务的访问,提供安全保护
精选场景详解 —— 文档服务:保护代理做权限校验
问题背景
DocumentService 能读取敏感合同。不能让所有调用方直接访问真实对象,需要在调用前鉴权、记审计日志,且对合法用户保持原有接口。
模式如何解决
选用保护代理:SecureDocumentProxy 与 RealDocumentService 实现同一 DocumentService 接口。代理先检查权限,通过后再委托真实对象;失败则拒绝。
代理家族还有远程代理、虚拟代理(懒加载)、缓存代理等,共同点是「控制访问并保持接口一致」。
与装饰器区别:装饰器聚焦功能叠加且常可多层嵌套;保护代理聚焦访问控制,通常不强调叠加同一职责的多层装饰。
场景模型(角色映射)
将模式中的抽象角色映射到该业务领域的具体类:
classDiagram
class DocumentService {
<<interface>>
+open(docId: String) Document
}
class RealDocumentService {
+open(docId: String) Document
}
class SecureDocumentProxy {
-real: RealDocumentService
-auth: AuthService
+open(docId: String) Document
}
class AuthService {
+canRead(user: User, docId: String) bool
}
class ClientApp {
+viewDoc(docId: String)
}
DocumentService <|.. RealDocumentService
DocumentService <|.. SecureDocumentProxy
SecureDocumentProxy --> RealDocumentService
SecureDocumentProxy --> AuthService
ClientApp --> DocumentService