我尝试在JDK、Android SDK和一些出名的库中,寻找静态代理的源码,没能找到。如果有读者发现,欢迎评论或者私信我。
本文目录
- 静态代理的实例
- 1. 售票代理
- 2. 明星代理
 
 
静态代理的实例
1. 售票代理
售票服务
public interface TicketService {  //售票  public void sellTicket();  //问询  public void inquire();  //退票  public void withdraw();  
}
站点售票
public class Station implements TicketService {  @Override  public void sellTicket() {  System.out.println("\n\t售票.....\n");  }  @Override  public void inquire() {  System.out.println("\n\t问询。。。。\n");  }  @Override  public void withdraw() {  System.out.println("\n\t退票......\n");  }  }
代理网点售票
public class StationProxy implements TicketService {  private Station station;  public StationProxy(Station station){  this.station = station;  }  @Override  public void sellTicket() {  // 1.做真正业务前,提示信息  this.showAlertInfo("××××您正在使用车票代售点进行购票,每张票将会收取5元手续费!××××");  // 2.调用真实业务逻辑  station.sellTicket();  // 3.后处理  this.takeHandlingFee();  this.showAlertInfo("××××欢迎您的光临,再见!××××\n");  }  @Override  public void inquire() {  // 1.做真正业务前,提示信息  this.showAlertInfo("××××欢迎光临本代售点,问询服务不会收取任何费用,本问询信息仅供参考,具体信息以车站真实数据为准!××××");  // 2.调用真实逻辑  station.inquire();  // 3。后处理  this.showAlertInfo("××××欢迎您的光临,再见!××××\n");  }  @Override  public void withdraw() {  // 1.真正业务前处理  this.showAlertInfo("××××欢迎光临本代售点,退票除了扣除票额的20%外,本代理处额外加收2元手续费!××××");  // 2.调用真正业务逻辑  station.withdraw();  // 3.后处理  this.takeHandlingFee();  }  /* * 展示额外信息 */  private void showAlertInfo(String info) {  System.out.println(info);  }  /* * 收取手续费 */  private void takeHandlingFee() {  System.out.println("收取手续费,打印发票。。。。。\n");  }  }
2. 明星代理
public interface IStar {public abstract void sing(double money);
}public class StarImpl implements IStar {public void sing(double money) {System.out.println("唱歌,收入" + money + "元");}
}//经纪人
public class StarProxy implements IStar {private StarImpl star = new StarImpl();public void sing(double money) {System.out.println("请先预约时间");System.out.println("沟通出场费用");if (money < 100000) {System.out.println("对不起,出场费10w万以内不受理");return;}System.out.println("经纪人抽取了" + money * 0.2 + "元代理费用");star.sing(money * 0.8);}
}//测试
public class ProxyDemo {public static void main(String[] args) {StarProxy sg = new StarProxy();sg.sing(200000);}
}