Definition of proxy pattern?
Definition of proxy mode: Provide a proxy for other objects to control access to this object. In some cases, an object is inappropriate or cannot directly reference another object, and a proxy object can act as an intermediary between the client and the target object. ( https://baike.baidu.com/item/proxy mode/8374046?fr=aladdin)
Let's first look at an example of a static proxy:
public interface MsgInterface {
void eat();
}
target class:
public class TargetObject implements MsgInterface {
@Override
public void eat() {
System.out.println("target eat...");
}
}
Proxy class:
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");
}
}
Write a main method:
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
Example of JDK dynamic proxy implementation:
https://blog.csdn.net/kevin_king1992/article/details/74095214
About the difference between proxy mode and decorator mode: https://blog.csdn.net/bigtree_3721/article/details/50840833
http://xvshell.iteye.com/blog/2363443
Send a question: Spring AOP is implemented in the proxy mode, but does it also conform to the decorator mode?
Reference:
http://www.runoob.com/design-pattern/proxy-pattern.html Proxy Pattern
http://www.runoob.com/design-pattern/decorator-pattern.html Decorator Pattern