1 package com.shejimoshi.structural.Proxy; 2 3 4 /** 5 * 功能:为其他对象提供一种代理以控制这个对象的访问 6 * 适用:1、远程代理,为一个对象在不同的地址空间提供局部代表 7 * 2、虚代理,根据需要创建开销很大的对象 8 * 3、保护代理,控制对原始对象的访问 9 * 4、智能指引,取代了简单的指针,它在访问对象时执行了一些附加操作10 * 时间:2016年2月29日上午10:13:5511 * 作者:cutter_point12 */13 public interface Person14 {15 public void surfTheInternet();16 }
1 package com.shejimoshi.structural.Proxy; 2 3 4 /** 5 * 功能:这个类代表自己 6 * 时间:2016年2月29日上午10:18:23 7 * 作者:cutter_point 8 */ 9 public class Myself implements Person10 {11 //自己交的话上网费12 private int money;13 private String name;14 15 public Myself(String name, int mon)16 {17 this.money = mon;18 this.name = name;19 }20 21 public Myself(Myself m)22 {23 this.money = m.money;24 this.name = m.name;25 }26 27 @Override28 public void surfTheInternet()29 {30 StringBuffer str = new StringBuffer(name);31 str.append("交了").append(money).append("元在上网");32 System.out.println(str.toString());33 }34 35 public int getMoney()36 {37 return money;38 }39 40 public void setMoney(int money)41 {42 this.money = money;43 }44 45 public String getName()46 {47 return name;48 }49 50 public void setName(String name)51 {52 this.name = name;53 }54 55 56 57 }
1 package com.shejimoshi.structural.Proxy; 2 3 4 /** 5 * 功能:别人带我交上网费用 6 * 时间:2016年2月29日上午10:22:07 7 * 作者:cutter_point 8 */ 9 public class Other implements Person10 {11 private int promoney; //代理费12 private String name; //代理人名13 private Myself cutter_point; //上网人14 15 public Other(String name, int mon, Myself cutter)16 {17 this.promoney = mon;18 this.name = name;19 //帮谁交多少钱20 cutter_point = new Myself(cutter);21 }22 23 @Override24 public void surfTheInternet()25 {26 StringBuffer str = new StringBuffer(name);27 str.append("代替").append(cutter_point.getName()).append("交了").append(cutter_point.getMoney()).append("元网费");28 str.append("收取了").append(promoney).append("元代理费");29 System.out.println(str.toString());30 }31 32 }
1 package com.shejimoshi.structural.Proxy; 2 3 4 /** 5 * 功能:测试代理功能 6 * 时间:2016年2月29日上午10:27:02 7 * 作者:cutter_point 8 */ 9 public class Test10 {11 public static void main(String[] args)12 {13 Other o = new Other("赵信", 2, new Myself("cutter_point", 20));14 o.surfTheInternet(); //这里是赵信去交网费,但是high的是cutter_point,没赵信什么事15 }16 }
显示结果:
赵信代替cutter_point交了20元网费收取了2元代理费
原标题:【设计模式】12、代理模式
关键词:设计模式