1、定义:为其他对象提供一种代理以控制对这个对象的访问。
2、代码:
代理接口:
public interface IGiveGift {
void giveMoney();
void giveCar();
void giveHouse();
}
实际对象:
public class RealRichBoy implements IGiveGift {
PrettyGirl girl;
public RealRichBoy(PrettyGirl girl){
this.girl = girl;
}
public void giveMoney() {
System.out.println(girl.getName() + "送你钱!");
}
public void giveCar() {
System.out.println(girl.getName() + "送你车!");
}
public void giveHouse() {
System.out.println(girl.getName() + "送你房!");
}
}
代理对象:
public class PoorRichBoy implements IGiveGift {
private RealRichBoy boy;
public PoorRichBoy (PrettyGirl girl) {
boy = new RealRichBoy(girl);
}
public void giveMoney() {
boy.giveMoney();
}
public void giveCar() {
boy.giveCar();
}
public void giveHouse() {
boy.giveHouse();
}
}
目标:
public class PrettyGirl {
private String name;
public PrettyGirl (String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试类:
public class Main {
public static void main(String[] args) {
PrettyGirl girl = new PrettyGirl("小美女");
PoorRichBoy boy = new PoorRichBoy(girl);
boy.giveMoney();
boy.giveCar();
boy.giveHouse();
}
}