There is no such thing as perfect programming, but we shouldn’t be discouraged because programming is a constant pursuit of perfection.

  1. The intent is to create a proxy for the object to control access to the object.
  2. The class diagram

  3. The instance
// static proxy interface ComProxyINF{void play(); } class implements ComProxyINF{@override public void play() {system.out.println (" implements -- "); } } class ComProxy implements ComProxyINF{ private ComProxyINF comProxyINF; public ComProxy(ComProxyINF comProxyINF){ this.comProxyINF = comProxyINF; } @override public void play() {system.out.println (" -- "); comProxyINF.play(); System.out.println(" proxy tail -- "); }} interface JDKProxyINF{void play(); } class implements JDKProxyINF{@override public void play() {system.out.println ("JDK -- "); Public void play(){system.out.println (" CG instance -- "); }}Copy the code
  1. test
Public static void main(String[] args) {// static void main(String[] args) {// static void main(String[] args); ComProxy comProxy = new ComProxy(new ComProxyImpl()); comProxy.play(); Println ("JDK dynamic proxy: "); JDKProxyINF jdkProxyImpl = new JDKProxyImpl(); JDKProxyINF jdkProxy = (JDKProxyINF)Proxy.newProxyInstance(jdkProxyImpl.getClass().getClassLoader(), new Class[]{JDKProxyINF.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {system.out.println ("JDK proxy header -- "); method.invoke(jdkProxyImpl, args); System.out.println("JDK agent tail -- "); return null; }}); jdkProxy.play(); // system.out.println (" CG: "); // system.out.println (" CG: "); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(CgProxyImpl.class); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Throws Throwable {system.out.println (" CG proxy header -- "); methodProxy.invokeSuper(o, objects); System.out.println(" CG proxy tail -- "); return null; }}); CgProxyImpl cgProxy = (CgProxyImpl) enhancer.create(); cgProxy.play(); }}Copy the code

Running results:

JDK dynamic proxy: JDK proxy header -- JDK instance -- JDK proxy tail -- CG dynamic proxy: CG proxy header -- CG instance -- CG proxy tail --Copy the code

Want to see more? Please visit:Design patterns