代理模式:
案例:静态代购模式
/**
* 购买者
*/
public class Buyer implements BuyMac {
private String name;
public Buyer(String name) {
this.name = name;
}
@Override
public void buyMac(String mac) {
System.out.println(this.name + "得到了一台" + mac);
}
}
/**
* 代购的规范
*/
public interface BuyMac {
void buyMac(String mac);
}
/**
* 代理模式:
* 代理,需要执行某些任务的时候,自己不去,找一些人帮助我去实现。
* 案例:
* 代购:小明、小美、小娟知道老王要出国,想让老王代购苹果电脑。
*/
public class Program {
public static void main(String[] args) {
// 实例化几个人
Buyer xiaoming = new Buyer("xiaoming");
Buyer xiaomei = new Buyer("xiaomei");
Buyer xiaojuan = new Buyer("xiaojuan");
// 实例化一个代理对象
Proxy laowang = new Proxy("laowang", xiaoming, xiaomei, xiaojuan);
// 让代理去买东西
laowang.buyMac("MacBook Pro");
}
}
/**
* 代购者
*/
public class Proxy implements BuyMac {
private String name;
BuyMac[] buyers; // 所有需要代购的人
public Proxy(String name, BuyMac... buyers) {
this.name = name;
this.buyers = buyers;
}
@Override
public void buyMac(String mac) {
System.out.println("代购员: " + this.name + "走进了Apple Store");
// 代购的过程
for (BuyMac buyer : this.buyers) {
// 为每一个代购者购买产品
buyer.buyMac(mac);
}
System.out.println("代购员: " + this.name + "走出了Apple Store");
}
}