以追女孩为例,需要人帮忙送礼物
实现
女孩
public class Girl {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Girl(String name){
this.name = name;
}
}
接口
public interface IGiveGift {
void sendFlower();
void sendSnack();
void sendChocolate();
}
男孩
public class Boy implements IGiveGift {
private Girl girl;
public Boy(Girl girl){
this.girl = girl;
}
@Override
public void sendFlower(){
System.out.println("给 "+this.girl.getName()+" 送花");
}
@Override
public void sendSnack(){
System.out.println("给 "+this.girl.getName()+" 送零食");
}
@Override
public void sendChocolate(){
System.out.println("给 "+this.girl.getName()+" 送巧克力");
}
}
代理同学
public class Proxy implements IGiveGift {
private Boy boy;
public Proxy(Girl girl){
this.boy = new Boy(girl);
}
@Override
public void sendFlower() {
System.out.println("代理同学,帮忙送花");
this.boy.sendFlower();
System.out.println("花送完了");
}
@Override
public void sendSnack() {
System.out.println("代理同学,帮忙送零食");
this.boy.sendSnack();
System.out.println("送完零食");
}
@Override
public void sendChocolate() {
System.out.println("代理同学,帮忙送巧克力");
this.boy.sendChocolate();
System.out.println("送完巧克力");
}
}
使用
public static void main(String[] args) {
Girl girl = new Girl("小丽");
Proxy proxy = new Proxy(girl);
proxy.sendChocolate();
}
打印
代理同学,帮忙送巧克力
给 小丽 送巧克力
送完巧克力
网友评论