interface GiveGift{
void GiveDolls();
void GiveFlowers();
}
class SchoolGirl{
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
class Pursuit implements GiveGift{
private SchoolGirl mm;
public Pursuit(SchoolGirl mm){
this.mm=mm;
}
public void GiveDolls() {
System.out.println("give Dolls to "+mm.getName());
}
@Override
public void GiveFlowers() {
System.out.println("give Flowers to "+mm.getName());
}
}
class Proxy implements GiveGift{
private Pursuit gg;
public Proxy(SchoolGirl mm){
gg=new Pursuit(mm);
}
@Override
public void GiveDolls() {
gg.GiveDolls();
}
@Override
public void GiveFlowers() {
gg.GiveFlowers();
}
}
public class TestProxy {
public static void main(String[] args){
SchoolGirl jiaojiao=new SchoolGirl();
jiaojiao.setName("jiaojiao");
Proxy daili=new Proxy(jiaojiao);
daili.GiveDolls();
daili.GiveFlowers();
}
}
表面上我们只能看见代理与schoolgirl的交互,其实是Pursuit类完成本质上的工作。
代理类与被代理的pursuit实现同一接口。我们可以在代理类加入自己的逻辑。比如调用被代理前日志打印。拦截特定信息。调用后的收尾操作。