Static Proxy (静态代理模式)

1.定义一个接口

ProxyInterface.java

[java] view plain copy
  1. package com.staticproxy ;  
  2.   
  3.   
  4. public interface ProxyInterface  //就假设为 定义一个购房的接口  
  5. {  
  6.     public void buyTest() ;//定义一个实现购房的方法规范  
  7. }  

2.定义一个真实角色实现了ProxyInterface接口

RealMaster.java

[java] view plain copy
  1. package com.staticproxy ;  
  2.   
  3. public class RealMaster implements ProxyInterface //定义一个真实的主人,也就是 房主  
  4. {  
  5.     public void buyTest()  
  6.     {  
  7.         System.out.println("实现购买房主的手续") ;  
  8.     }  
  9. }  

3.定义一个代理角色,实现了ProxyInterface接口,还持有一个 真实主人对象的引用

ProxyMaster.java

[java] view plain copy
  1. package com.staticproxy ;  
  2.   
  3. public class ProxyMaster implements ProxyInterface //定义一个代理主人,就相当于 中介,  
  4. {  
  5.     private RealMaster rm;//持有一个 真实主人对象的引用    
  6.   
  7.     public void buyTest()  
  8.     {  
  9.         this.beforeTest() ; //中介 一开始 收取买主 的介绍费  
  10.   
  11.         this.rm = new RealMaster() ;  
  12.   
  13.         rm.buyTest() ;   
  14.           
  15.         this.afterTest() ; // 购完房 中介要收取的费用  
  16.   
  17.     }  
  18.   
  19.     public void beforeTest()  
  20.     {  
  21.         System.out.println("中介 一开始 的介绍费") ;  
  22.     }  
  23.   
  24.     public void afterTest()  
  25.     {  
  26.         System.out.println("购完房 中介要收取的费用") ;  
  27.     }  
  28. }  

4.客户端 Client.java

[java] view plain copy
  1. package com.staticproxy ;  
  2.   
  3. public class Client //定义一个客户端  
  4. {  
  5.     public static void main(String[] args)  
  6.     {  
  7.         ProxyMaster pm = new ProxyMaster() ;  
  8.           
  9.         pm.buyTest() ;  
  10.   
  11.     }  
  12. }  
原文地址:https://www.cnblogs.com/hoobey/p/5294403.html