代理模式的定义?
代理模式的定义:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。(https://baike.baidu.com/item/代理模式/8374046?fr=aladdin)
先来看一下静态代理的例子:
public interface MsgInterface {
void eat();
}
目标类:
public class TargetObject implements MsgInterface {
@Override
public void eat() {
System.out.println("target eat...");
}
}
代理类:
public class ProxyObject implements MsgInterface {
private TargetObject target;
ProxyObject(TargetObject target){
this.target = target;
}
@Override
public void eat() {
befare();
target.eat();
after();
}
private void befare() {
System.out.println("befare eat,wash hand");
}
private void after() {
System.out.println("after eat,clean all");
}
}
写一个main方法:
public class ProxyDemo {
public static void main(String[] args) {
MsgInterface i = new ProxyObject(new TargetObject());
i.eat();
}
}
结果:
befare eat,wash hand
target eat…
after eat,clean all
JDK动态代理实现的例子:
https://blog.csdn.net/kevin_king1992/article/details/74095214
关于代理模式与装饰器模式的区别:https://blog.csdn.net/bigtree_3721/article/details/50840833
http://xvshell.iteye.com/blog/2363443
发一个问:Spring AOP是代理模式实现的,但是是否也符合装饰器模式呢?
参考:
http://www.runoob.com/design-pattern/proxy-pattern.html 代理模式
http://www.runoob.com/design-pattern/decorator-pattern.html 装饰器模式