静态代理:
public class StaticProxy
{
public static void main(String[] args)
{
User user = new UserImpl();
UserProxy proxy = new UserProxy(user);
proxy.printInfo();
}
}
/**
* 委托接口
*/
interface User
{
void printInfo();
}
/**
* 委托类
*/
class UserImpl implements User
{
@Override
public void printInfo()
{
System.out.println("hello i am world");
}
}
/**
* 代理类
*/
class UserProxy implements User
{
private User user;
/**
* @param user
*/
public UserProxy(User user)
{
this.user = user;
}
@Override
public void printInfo()
{
before();
user.printInfo();
after();
}
private void before()
{
System.out.println(" invoke before");
}
private void after()
{
System.out.println("invoke after");
}
}
我们发现,静态代理其实就是组合模式,自己要调用的方法通过自己的属性来调用。
动态代理:
像spring里的aop机制就是用的动态代理,在执行主业务方法前后都可以来记录日志等非业务方法。
public class StaticProxy
{
public static void main(String[] args)
{
User user = new UserImpl(); // 委托对象 //代理第一个接口
InvocationHandler hander = new UserProxy(user);// 代理对象
/** 注意下面两个getClass()的主对象,一个是代理对象,一个是委托对象 * */
User userProxy =
(User) Proxy.newProxyInstance(hander.getClass().getClassLoader(),
user.getClass().getInterfaces(),
hander);
System.out.println(userProxy.getClass().getName()); // 它并不是输出USER这个类的路径,而是一个代理类
userProxy.printInfo(); // 并没有实际的调用invoke方法,而是隐性地调用的。
userProxy.sendMessage("hello");
Worker worker = new WorkImpl(); //代理第二个接口
InvocationHandler handler2 = new UserProxy(worker); // 重新为Worker接口代理,代理类不用重写,因为代理类与具体的委托对象无关
Worker workerProxy =
(Worker) Proxy.newProxyInstance(handler2.getClass().getClassLoader(), worker.getClass()
.getInterfaces(), handler2);
workerProxy.hello();
}
}
interface Worker
{
void hello();
}
class WorkImpl implements Worker
{
@Override
public void hello()
{
System.out.println("work success");
}
}
/**
* 委托接口
*/
interface User
{
void printInfo();
void sendMessage(String msg);
}
/**
* 委托类
*/
class UserImpl implements User
{
@Override
public void printInfo()
{
System.out.println("hello i am world");
}
@Override
public void sendMessage(String msg)
{
System.out.println(msg);
}
}
/**
* 代理类
*/
class UserProxy implements InvocationHandler
{
/** 所有的方法调用都会经过这个入口来反射调用 * */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
System.out.println(method);
System.out.println("invoke beforer");
method.invoke(object, args); // 这里并不是引用的proxy这个对象,而是注入的委托对象object
System.out.println("invoke after");
return null;
}
private Object object;
/**
* @param user
*/
public UserProxy(Object object)
{
this.object = object;
}
}
输出:
com.chenjun.$Proxy0
public abstract void com.chenjun.User.printInfo()
invoke beforer
hello i am world
invoke after
public abstract void com.chenjun.User.sendMessage(java.lang.String)
invoke beforer
hello
invoke after
public abstract void com.chenjun.Worker.hello()
invoke beforer
work success
invoke after
这样的话,就可以代理多个接口,只需要重写接口及实现类即可,代理类可通用,而静态代理的方法是根据具体对象调用写死的,只能调用一个接口里的方法,不是很常用