java 代理模式(静态代理+动态代理)


静态代理:

ISubject:


/*
  @author com.tiantian
@version 创建时间:2012-11-20 下午1:49:29
/
public interface ISubject {
public void request();
}

RealSubject(真实角色):


/*
  @author com.tiantian
@version 创建时间:2012-11-20 下午1:51:37
/
public class RealSubject implements ISubject{

@Override
public void request() {
System.out.println(
“realSubject requesting”);
}
}

ProxySubject(代理类):


/*
  @author com.tiantian
@version 创建时间:2012-11-20 下午1:52:22
/
public class ProxySubject implements ISubject{
private RealSubject realSubject;
public ProxySubject() {
realSubject
= new RealSubject();
}

@Override
public void request() {
System.out.println(
“do something before”);
realSubject.request();
System.out.println(
“do something after”);
}
}

Test(客户端测试):


/*
  @author com.tiantian
@version 创建时间:2012-11-20 下午1:54:47
/
public class Test {
public static void main(String[] args) {
ISubject proxySubject
= new ProxySubject();
proxySubject.request();
}
}


动态代理:

ISubject:


/*
  @author com.tiantian
@version 创建时间:2012-11-20 下午2:51:31
/
public interface ISubject {
public void request();
}

RealSubject:


/*
  @author com.tiantian
@version 创建时间:2012-11-20 下午2:52:00
/
public class RealSubject implements ISubject{

@Override
public void request() {
System.out.println(
“realSubject requesting”);
}
}

SubjectInvocationHandler(调用处理类):


/
@author com.tiantian @version 创建时间:2012-11-20 下午2:54:38
调用处理类
/
public class SubjectInvocationHandler implements InvocationHandler{
private Object obj;

public SubjectInvocationHandler(Object obj) {
this.obj = obj;
}

/
生成代理类工厂
@author com.tiantian
@param realObj @return 返回生成的代理类
*/
public static Object getProxyInstanceFactory(Object realObj){
Class
<?> classType = realObj.getClass();
return Proxy.newProxyInstance(classType.getClassLoader(),
classType.getInterfaces(),
new SubjectInvocationHandler(realObj));
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(
“before”);

method.invoke(obj, args);

System.out.println(
“after”);

return null;
}
}

Test:


/*
  @author com.tiantian
@version 创建时间:2012-11-20 下午2:56:25
/
public class Test {
public static void main(String[] args) {
RealSubject realSubject
= new RealSubject();
// InvocationHandler handler = new SubjectInvocationHandler(realSubject);
// ISubject subject = (ISubject)Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),
// realSubject.getClass().getInterfaces(), handler);
ISubject subject = (ISubject)SubjectInvocationHandler.getProxyInstanceFactory(realSubject);
subject.request();

}
}

 

 

 



来源博客:Wang Jie's Blog
本文链接:https://blog.wangjiegulu.com/2012/11/20/java-代理模式(静态代理-动态代理)/
版权声明:本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处。