题目:一个男孩让另一个男孩代理去送一个女孩礼物
public class SchoolGirl { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; }}
public interface GiveGift { void giveDoll(); void giveFlower(); void giveChocolate();}
public class Pursuit implements GiveGift { SchoolGirl mm; public Pursuit(SchoolGirl mm) { this.mm = mm; } @Override public void giveDoll() { System.out.println(mm.getName() + "送你洋娃娃"); } @Override public void giveFlower() { System.out.println(mm.getName() + "送你鲜花"); } @Override public void giveChocolate() { System.out.println(mm.getName() + "送你巧克力"); }}
public class Proxy implements GiveGift { Pursuit gg; public Proxy(SchoolGirl mm) { gg = new Pursuit(mm); } @Override public void giveDoll() { gg.giveDoll(); } @Override public void giveFlower() { gg.giveFlower(); } @Override public void giveChocolate() { gg.giveChocolate(); }}
public class Action { public static void main(String args[]) { SchoolGirl jiaojiao = new SchoolGirl(); jiaojiao.setName("李娇娇"); Proxy daili = new Proxy(jiaojiao); daili.giveDoll(); daili.giveFlower(); daili.giveChocolate(); }}
打印结果:
李娇娇送你洋娃娃李娇娇送你鲜花李娇娇送你巧克力
原理就是:
1.Pursuit和Proxy都实现了GiveGift接口,但Proxy中实际调用的也是Pursuit的方法
2.Proxy的构造函数也是为了生成Pursuit的对象
3.所以在Action中,我们只看到了Proxy在忙来忙去,Pursuit被隐藏了起来