知识卡片
代理模式的定义与三个角色
代理通过替身控制目标对象的访问。Subject定义客户使用的契约,RealSubject实现业务,Proxy实现相同契约并持有目标引用,可转发或在边界增加控制。
游戏例的代理转发login、killBoss和upgrade;客户可用IGamePlayer引用它,不必依赖具体代理类型。代理并非总是不可感知,也不能把所有委托都称为代理:策略、状态等意图不同。图按实际签名,构造器参数以代码的IGamePlayer为准,未执行。
结构图:
classDiagram
class IGamePlayer {
<<interface>>
+login(String user,String password) void
+killBoss() void
+upgrade() void
}
class GamePlayer {
+GamePlayer(String name)
}
class GamePlayerProxy {
+GamePlayerProxy(IGamePlayer gamePlayer)
}
IGamePlayer <|.. GamePlayer
IGamePlayer <|.. GamePlayerProxy
GamePlayerProxy --> IGamePlayer : 转发相同契约
通用示例默认构造器内部new Proxy会递归构造自身,不能按此作为默认目标;后文Proxy(Subject)才明确注入被代理对象。顺序before→目标→after中,目标抛异常会跳过after,清理若必须执行应有明确异常处理,而非由模式自动保证。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 2 处
- 第12章 代理模式 · 查看原书依据
public class GamePlayerProxy implements IGamePlayer { private IGamePlayer gamePlayer = null; //通过构造函数传递要对谁进行代练 public GamePlayerPr
- 12.2 代理模式的定义 · 查看原书依据
public Proxy(){ this.subject = new Proxy(); } //通过构造函数传递代理者 public Proxy(Object...objects ){ } //实现接口中定义的方法 public void request()
参考来源
- 位置:《设计模式之禅(第2版)》第12章 代理模式(来源项目book-sources,源文件:extracted/设计模式之禅(第2版)/_epub-src/text/part0052.html)
- 结论依据:原文定义、示例及取舍支撑本卡;已知过强表述在正文限定。
- 原始内容:public class GamePlayerProxy implements IGamePlayer { private IGamePlayer gamePlayer = null; //通过构造函数传递要对谁进行代练 public GamePlayerPr
- 补充位置:12.2 代理模式的定义(源文件:extracted/设计模式之禅(第2版)/_epub-src/text/part0053.html);补充原始内容:public Proxy(){ this.subject = new Proxy(); } //通过构造函数传递代理者 public Proxy(Object...objects ){ } //实现接口中定义的方法 public void request()