注:本文为译文,原文出处java-design-patterns-in-stories
本文翻译自一个国外网站, 它用一个古老的故事来描述设计模式.
我很忙以至于不能回复你的请求, 因此会转到我的代理. 代理应该知道委派者能做什么. 也就是说, 它们有着相同的接口. 代理不能做这个工作, 但是委派者可以. 这些你不能理解的特性可以全部忽略.
这是一个有趣的故事, 我翻译自”Water Margin”. 可以能在我翻译过后它听起来就没那么好笑了, 但不管怎样, 你了解到了代理模式的思想.
故事如下:
一些坏人, 不论说明原因, 总是想和一些好人的妻子OOXX. 在这些妻子中间, 一些人想和那些坏人OOXX, 其他人则不愿意. 坏人也不能直接询问这些妻子. 因为他不确定他问的这个人是否想和他做这些肮脏的事儿. 如果他做了一个错误的判断, 他会陷入一个非常糟糕的境地. 因此会有一个代理来帮他做这种事情.
这种情况下会有如下角色:
interface CheatingWife {
// think about what this kind of women can do
public void seduceMan(); // such as eye contact with men
public void happyWithMan(); // happy what? You know that.
}
class HouseWifeOne implements CheatingWife {
public void seduceMan() {
System.out
.println("HouseWifeOne seduce men, such as making some sexy poses ...");
}
public void happyWithMan() {
System.out.println("HouseWifeOne is happy with man ...");
}
}
class BusinessAgent implements CheatingWife {
private CheatingWife cheatingWife;
public BusinessAgent() {
this.cheatingWife = new HouseWifeOne();
}
public BusinessAgent(CheatingWife cheatingWife) {
this.cheatingWife = cheatingWife;
}
public void seduceMan() {
this.cheatingWife.seduceMan();
}
public void happyWithMan() {
this.cheatingWife.happyWithMan();
}
}
// see? it looks that agent/proxy is doing
public class Mike {
public static void main(String[] args) {
BusinessAgent businessAgent = new BusinessAgent();
businessAgent.seduceMan();
businessAgent.happyWithMan();
}
}