代理模式,就是找一个代理把你要做的事都通过它来做,找代理的原因有很多种,比如男生追女生可能不好意思,所以找个同学帮忙,比如要电话号码、传递情书等等,表面上是你同学和那个女生接触,实际上这些动作都是有你来执行,你同学只是一个代理你的动作、还有的情况可能是有些情况两者之间是不能直接通信,比如我们在淘宝上买东西付钱,表面上我们是给卖我们商品的店家付钱,实际上是把钱先打给了淘宝,等到一定时间后,客户收到商品,没有什么问题后,再由淘宝把钱转给商家,这其实也是一种安全措施~
/**
* Author:小民
*/
//定义一个抽象的卖家类型
public interface ISeller{
public void sell();
public void acceptMoney();
}
//定义淘宝类
public class Taobao implements ISeller{
ISeller seller;
public Taobao(ISeller seller)
{
this.seller=seller;
}
public void sell()
{
seller.sell();
}
public void acceptMoney(){
//经过一段时间后,用户没有提出问题,钱自动转到对于的商家账户
try {
Thread.sleep(1000000);
seller.acceptMoney();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//定义淘宝上的商家,比如买手机的
public class Iphone implements ISeller{
public void sell(){
System.out.println("卖出一台苹果手机");
}
public void acceptMoney()
{
System.out.println("收了5580块钱");
}
}
//定义淘宝上的商家,比如买手机的
public class Shoes implements ISeller{
public void sell(){
System.out.println("卖出一双鞋");
}
public void acceptMoney()
{
System.out.println("收了2000块钱");
}
}
//测试主函数
public class Test{
public static void Main(String[] args)
{
Shoes shoes=new Shoes();
Taobao taobao=new Taobao(shoes);
taobao.sell();
taobao.acceptMoney();
Iphone iphone=new Iphone();
taobao=new Taobao(iphone);
taobao.acceptMoney();
}
}