标签:log color ret class 学习 代理模式 来讲 int ati
To be, or not to be: that is the question.
——《哈姆雷特》
代理模式(Proxy),为其他对象提供一种代理以控制对这个对象的访问。
上代码:
1 package cn.no4.proxy; 2 3 public interface IMakeMoney { 4 5 void makeMoney(); 6 }
1 package cn.no4.proxy; 2 3 public class Proxy implements IMakeMoney { 4 5 private Boss boss; 6 7 public Proxy() { 8 boss = new Boss(); 9 } 10 11 @Override 12 public void makeMoney() { 13 System.out.println("表面上是proxy在做事情..."); 14 boss.makeMoney(); 15 } 16 17 }
1 package cn.no4.proxy; 2 3 public class Boss implements IMakeMoney{ 4 5 private double money; 6 7 8 public double getMoney() { 9 return money; 10 } 11 12 13 public void setMoney(double money) { 14 this.money = money; 15 } 16 17 18 @Override 19 public void makeMoney() { 20 21 money += 5000000; 22 System.out.println("实际上是幕后黑手大boss干的,大boss得到了$"+money); 23 } 24 25 }
测试类:
1 package cn.no4.proxy; 2 3 public class _Test { 4 5 public static void main(String[] args) { 6 Proxy proxy = new Proxy(); 7 proxy.makeMoney(); 8 } 9 }
下面修改了Proxy类的makeMoney方法,实现了对boss对象访问的控制:
1 package cn.no4.proxy.instance; 2 3 public class Proxy implements IMakeMoney { 4 5 private Boss boss; 6 7 public Proxy() { 8 boss = new Boss(); 9 } 10 11 @Override 12 public void makeMoney(double money) { 13 System.out.println("表面上是proxy在做事情..."); 14 //以下代码实现了对boss访问的控制 15 if (money < 5000000.0) { 16 System.out.println("钱太少,打发要饭的呢!"); 17 }else{ 18 boss.makeMoney(money); 19 } 20 } 21 22 }
测试类:
1 package cn.no4.proxy.instance; 2 3 public class _Test { 4 5 public static void main(String[] args) { 6 Proxy proxy = new Proxy(); 7 proxy.makeMoney(1); 8 proxy.makeMoney(5000000); 9 } 10 }
proxy.makeMoney(1);无法访问到boss对象,因为1块钱对于boss来讲太少了
proxy.makeMoney(5000000);这下可以访问到boss对象了,执行了boss的makeMoney方法
标签:log color ret class 学习 代理模式 来讲 int ati
原文地址:http://www.cnblogs.com/tomasman/p/6851541.html