背景:
接口(方法)。程序员:实现需求,具体角色。 产品经理:静态代理。
静态实现
接口代码:(程序员)
public interface ICode {
public void impDemands(String demandName);
public void updateDemands(String demandName);
}
具体执行类:
public class JavaCoder implements ICode{
private String name;
public JavaCoder(String name){
this.name=name;
}
@Override
public void impDemands(String demandName) {
System.out.println(name + " implemant demand: " +demandName+ " in java");
}
@Override
public void updateDemands(String demandName) {
System.out.println(name+" update demand " + demandName + " in net ");
}
}
代理类:(产品经理)
public class CodeProxy implements ICode{
private ICode code;
public CodeProxy(ICode code){
this.code=code;
}
/**
* 实现需求
*/
@Override
public void impDemands(String demandName) {
if(demandName.contains("add")){
System.out.println("no!");
return;
}
code.impDemands(demandName);
}
/**
* 修改需求
*/
@Override
public void updateDemands(String demandName) {
code.updateDemands(demandName);
}
}
客户提出需求给代理:
public class Customer {
public static void main(String[] args) {
//创建真是脚色实例
JavaCoder code=new JavaCoder("lou");
//创建代理角色实例
CodeProxy proxy=new CodeProxy(code);
//通过代理具体实现
//proxy.impDemands(" add user ");
proxy.updateDemands(" kill user ");
}
}
动态实现:
背景:若是在每个方法的执行前后输出时间。动态代理比较合适。
中介类:
public class CoderDynamicProxy implements InvocationHandler{
//被代理类实例
private ICode code;
public CoderDynamicProxy(ICode _code){
this.code=_code;
}
//调用被代理的方法
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(System.currentTimeMillis());
Object result=method.invoke(code, args);
System.out.println(System.currentTimeMillis());
return result;
}
}
具体实现:
public class DynamicClient {
public static void main(String[] args) {
//要代理的真实对象
ICode coder=new JavaCoder("zhang");
//创建中介类实例
InvocationHandler handler= new CoderDynamicProxy(coder);
//获取类加载器
ClassLoader loader = coder.getClass().getClassLoader();
//动态产生一个代理类
ICode proxy = (ICode)Proxy.newProxyInstance(loader, coder.getClass().getInterfaces(), handler);
//通过代理类执行方法
proxy.impDemands("start.........");
proxy.updateDemands(" kill user ");
}
}