Java 设计模式 之 代理模式
http://www.verejava.com/?id=16999158881575
package com.proxy.theory;
public class TestProxy
{
public static void main(String[] args)
{
//要做的目标
Target target=new Target();
//我来处理目标
MyHandler myhandler=new MyHandler();
myhandler.setTarget(target);
//代码帮助处理目标
MyProxy proxy=new MyProxy();
proxy.setMyHandler(myhandler);
//TargetInterface ti=(TargetInterface)proxy.getProxy(target);
//ti.doSomething();
TargetInterface2 ti=(TargetInterface2)proxy.getProxy(target);
ti.study();
}
}
package com.proxy.theory;
public interface TargetInterface
{
public void doSomething();
}
package com.proxy.theory;
public interface TargetInterface2
{
public void study();
}
package com.proxy.theory;
public class Target implements TargetInterface,TargetInterface2
{
@Override
public void doSomething()
{
System.out.println("注册公司");
}
@Override
public void study()
{
System.out.println("去留学");
}
}
package com.proxy.theory;
import java.lang.reflect.Proxy;
public class MyProxy
{
private MyHandler myhandler;
public void setMyHandler(MyHandler myhandler)
{
this.myhandler=myhandler;
}
public Object getProxy(Object target)
{
//代理帮助 返回 myhandler 要处理的所有 可能的接口
return Proxy.newProxyInstance(MyProxy.class.getClassLoader(), target.getClass().getInterfaces(), myhandler);
}
}
package com.proxy.theory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyHandler implements InvocationHandler
{
private Object target;
public void setTarget(Object target)
{
this.target=target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
System.out.println("before");
method.invoke(target, args);
System.out.println("after");
return null;
}
}