To be, or not to be: that is the question.
——《哈姆雷特》
代理模式(Proxy),为其他对象提供一种代理以控制对这个对象的访问。
上代码:
package cn.no4.proxy; public interface IMakeMoney { void makeMoney();
}
package cn.no4.proxy; public class Proxy implements IMakeMoney { private Boss boss; public Proxy() {
boss = new Boss();
} @Override
public void makeMoney() {
System.out.println("表面上是proxy在做事情...");
boss.makeMoney();
} }
package cn.no4.proxy; public class Boss implements IMakeMoney{ private double money; public double getMoney() {
return money;
} public void setMoney(double money) {
this.money = money;
} @Override
public void makeMoney() { money += ;
System.out.println("实际上是幕后黑手大boss干的,大boss得到了$"+money);
} }
测试类:
package cn.no4.proxy; public class _Test { public static void main(String[] args) {
Proxy proxy = new Proxy();
proxy.makeMoney();
}
}
下面修改了Proxy类的makeMoney方法,实现了对boss对象访问的控制:
package cn.no4.proxy.instance; public class Proxy implements IMakeMoney { private Boss boss; public Proxy() {
boss = new Boss();
} @Override
public void makeMoney(double money) {
System.out.println("表面上是proxy在做事情...");
//以下代码实现了对boss访问的控制
if (money < 5000000.0) {
System.out.println("钱太少,打发要饭的呢!");
}else{
boss.makeMoney(money);
}
} }
测试类:
package cn.no4.proxy.instance; public class _Test { public static void main(String[] args) {
Proxy proxy = new Proxy();
proxy.makeMoney();
proxy.makeMoney();
}
}
proxy.makeMoney(1);无法访问到boss对象,因为1块钱对于boss来讲太少了
proxy.makeMoney(5000000);这下可以访问到boss对象了,执行了boss的makeMoney方法