1. Static Proxy
Abstract topic: Subject
Public interface Subject {public String Add ();}
Target object: Resubject
public class Resubject implements Subject {public String Add () { System.out.println ("ok!"); Return ""; }}
Proxy object: Psubject
public class Psubject implements Subject { private Subject resubject; Public Subject Getresubject () { return resubject; } public void Setresubject (Subject resubject) { this.resubject = resubject; } Public String Add () { System.out.println ("Open! "); return Resubject.add (); }}
One side
Static proxy @Test public void test12 () { Subject subject=new resubject (); Psubject psubject=new psubject (); Psubject.setresubject (subject); Psubject.add (); }
2. Dynamic Agent
Interface
Public interface Iuserdao {public String Add (); Public String edit ();}
Class
public class Userdaoimpl implements iuserdao{public String Add () { System.out.println ("add"); return "Add"; } Public String edit () { System.out.println ("edit"); Return "edit";} }
One side
Dynamic proxy @Test public void test13 () { final Iuserdao dao=new Userdaoimpl (); Iuserdao pp= (Iuserdao) proxy.newproxyinstance (Dao.getclass (). getClassLoader (), Dao.getclass (). GetInterfaces (), New Invocationhandler () {Public object Invoke (Object proxy, Method method, object[] args) throws Throwable { Syste M.out.println ("open"); Method.invoke (Dao,args); return null; } }); Pp.add (); Pp.edit (); }
3.cglib Dynamic Agent
public class UserService {public void Delete () { System.out.println ("OK");} }
One side (two ways)
/*cglib Dynamic Agent * /@Test public void test14 () { final userservice servive=new userservice (); Enhancer enhancer=new Enhancer (); Enhancer.setsuperclass (Servive.getclass ()); Enhancer.setcallback (New Methodinterceptor () {Public object intercept (Object o, Method, object[] objects, Methodproxy methodproxy) throws Throwable { System.out.println ("open"); Methodproxy.invoke (servive,objects); return null; } }); /* Enhancer.setcallback (New Org.springframework.cglib.proxy.InvocationHandler () {Public object invoke (Object o , method, object[] objects) throws Throwable { System.out.println ("open"); Method.invoke (servive,objects); return null; } }); */ UserService AA = (userservice) enhancer.create (); Aa.delete (); }
Spring Proxy mode