1、源接口
1 package Proxy;2 3 public interface Sourceable {4 public void method();5 6 }
2、实现类
1 package Proxy; 2 3 public class Source implements Sourceable{ 4 5 @Override 6 public void method() { 7 System.out.println("接口实现类中原始方法。"); 8 9 }10 11 }
3、代理类
1 package Proxy; 2 3 public class Proxy implements Sourceable{ 4 private Source source; 5 public Proxy(){ 6 super(); 7 //被代理类 8 this.source = new Source(); 9 }10 @Override11 public void method() {12 // TODO Auto-generated method stub13 before();14 source.method(); //在原始方法前后再扩展方法15 after();16 17 }18 public void after(){19 System.out.println("扩展方法1");20 }21 public void before(){22 System.out.println("扩展方法2");23 }24 25 }
4、客户端
1 package Proxy; 2 3 public class ProxyTest { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Sourceable source = new Proxy(); 8 source.method(); 9 }10 11 }
5、结果
扩展方法2接口实现类中原始方法。扩展方法1