代理模式
代理模式主要思考的场景是将业务以外的功能转移到代理中,让开发者集中于业务思考。
例如说讲一些非业务功能转移到代理类,比较典型的是RPC调用,将RPC中通讯、编解码等转移到代理类中,在业务接口调用中编程者只关注业务。
代理模式例子
public interface IProxy {
public void doit();
}
public class AProxy implements IProxy {
@Override
public void doit() {
System.out.println("do A");
}
}
public class MyService {
private final IProxy proxy;
public MyService(IProxy proxy) {
this.proxy = proxy;
}
public void doService() {
proxy.doit();
}
public static void main(String[] args) {
new MyService(new AProxy()).doService();
}
}
动态代理
动态代理也是代理模式,动态代理实现原理也不复杂。例子如下:
public interface ISubject {
void hello(String para);
}
public class MySubject implements ISubject{
@Override
public void hello(String para) {
System.out.println("hello");
}
}
public class DProxy implements InvocationHandler {
private final ISubject subject;
public DProxy(ISubject subject) {
this.subject = subject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("--------------begin-------------");
Object invoke = method.invoke(subject, args);
System.out.println("--------------end-------------");
return invoke;
}
public static void main(String[] args) {
ISubject subject = new MySubject();
InvocationHandler subjectProxy = new DProxy(subject);
ISubject proxyInstance = (ISubject) Proxy.newProxyInstance(subjectProxy.getClass().getClassLoader(), subject.getClass().getInterfaces(), subjectProxy);
proxyInstance.hello("world");
}
}
AOP
AOP的底层原理就是动态代理,Spring通过注解,进行面向切面的编程。把附加功能或公共功能放在各种切面中。
小结
动态代理只是类级别的模式,通过动态代理,上升到框架模块级别的使用。大模式由小模式演变而来。
网友评论