客户端与接口交互
proxy与具体类都需事先接口
proxy用于额外实现织入的内容
例子
接口类
public interface Subject {
void request();
void hello();
}
真正实现类
public class RealSubject implements Subject{
@Override
public void request() {
System.out.println("real subject execute request");
}
@Override
public void hello() {
System.out.println("hello");
}
}
代理类
public class Proxy implements Subject{
// 代理类中引用实际实现类
private RealSubject realSubject;
public Proxy(RealSubject realSubject) {
this.realSubject = realSubject;
}
// 在实际对象执行相应逻辑的前后通过代理对象添加额外的逻辑功能
@Override
public void request() {
System.out.println("before");
try{
realSubject.request();
}catch (Exception e){
System.out.println("ex:"+e.getMessage());
throw e;
}finally {
System.out.println("after");
}
}
@Override
public void hello() {
realSubject.hello();
}
}
客户端
public class Client {
public static void main(String[] args){
Subject subject = new Proxy(new RealSubject());
subject.request();
}
}