静态代理(Static proxy)
public interface IHello {
public void hello(String name);
}
/**
* 定义原有的不能修改的业务类,
* 现在的任务:在不修改此类的前提下,完成打印日志等其他事情
*/
public class HelloStaticProxy implements IHello {
@Override
public void hello(String name) {
System.out.println("hello=="+name);
}
}
/**
* 静态代理类
* 静态代理,需要为被代理对象和方法实现撰写特定的代理对象
*/
public class PrintLogStaticProxy implements IHello {
Logger logger = LoggerFactory.getLogger(PrintLogStaticProxy.class);
private IHello helloObject;
//有参数的构造方法,将参数传递给IHello,然后用helloObject,调用之前的方法,
//
public PrintLogStaticProxy(IHello helloObject){
this.helloObject=helloObject;
}
//在重写的hello方法前面实现,前后打印日志的功能
@Override
public void hello(String name) {
logger.info("hello"+name+"方法开始启动");
helloObject.hello(name);
logger.info("hello"+name+"方法执行完毕");
}
}
public class TestStaticProxy {
public static void main(String[] args) {
//不修改原有的类的基础上,修改调用类的地方,使其能加上打印日志等其他功能
IHello proxy=new PrintLogStaticProxy(new HelloStaticProxy());
proxy.hello("sunyuhua");
}
}
动态代理(Dynamic proxy)
public class PrintLogDecimalProxy implements InvocationHandler {
Logger logger=LoggerFactory.getLogger(PrintLogDecimalProxy.class);
private Object delegate;
public Object bind(Object delegate){
this.delegate=delegate;
return Proxy.newProxyInstance( delegate.getClass().getClassLoader(),
delegate.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result=null;
try {
logger.info("方法调用开始");
result = method.invoke(delegate, args);
logger.info("方法调用结束");
} catch (Exception e){
logger.info(e.toString());
}
return result;
}
}
public class TestDecimalProxy {
public static void main(String[] args) {
PrintLogDecimalProxy printLogDecimalProxy=new PrintLogDecimalProxy();
IHello hello=(IHello)printLogDecimalProxy.bind(new HelloStaticProxy());
hello.hello("sunyuhua??");
}
}