UML圖,為了展示核心的代理模式類關系,這裡細節的部分,比如Pursui和SchoolGirl的關系就不畫了,代理模式的核心為代理類和被代理類實作的是同一個接口,可以詳細控制通路某個類的方法,在調用方法前做前置處理,在調用方法後做後置處理
代碼結構
public class Client {
public static void main(String[] args) {
SchoolGirl jiaojiao = new SchoolGirl("李嬌嬌");
Proxy dali = new Proxy(jiaojiao);
dali.giveDolls();
dali.giveFlowers();
}
}
public interface IGiveGift {
void giveDolls();
void giveFlowers();
}
public class Proxy implements IGiveGift {
private Pursuit gg;
public Proxy(SchoolGirl mm) {
gg = new Pursuit(mm);
}
@Override
public void giveDolls() {
if(gg != null) {
gg.giveDolls();
}
}
@Override
public void giveFlowers() {
if(gg != null) {
gg.giveFlowers();
}
}
}
public class Pursuit implements IGiveGift {
private SchoolGirl schoolGirl;
public Pursuit(SchoolGirl schoolGirl) {
super();
this.schoolGirl = schoolGirl;
}
@Override
public void giveDolls() {
System.out.println(schoolGirl.getName() + ", 送你洋娃娃");
}
@Override
public void giveFlowers() {
System.out.println(schoolGirl.getName() + ", 送你鮮花");
}
}
public class SchoolGirl {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SchoolGirl(String name) {
super();
this.name = name;
}
}
運作結果