代理模式-积木模式
代理模式在实际开发中的确非常常见和常用,表面上代理模式是产生出一个代理类,作为访问实际实现类的代理,控制了外界对实际代理类的访问,在此基础上增加一些增强性的功能。实际上,还将实际实现作为一个粒度,将增强的部分功能分离解耦。
这里记录一下实现的一些代码:
静态代理:
public interface Subject { void toilet(); } public class RealSubject implements Subject{ public void toilet() { System.out.println("toilet"); } } /** * 代理类控制了真实角色的访问权限 * 而从代理类自身增强的角度来看,可以说是控制了被代理功能的粒度细分的控制 */ public class SubjectProxy implements Subject{ Subject subject = new RealSubject(); public void toilet() { System.out.println("take my phone"); subject.toilet(); System.out.println("smell bad"); } }
动态代理(java proxy):
public class ProxyHandler implements InvocationHandler { private Object object; public ProxyHandler() { } public ProxyHandler(Object object) { this.object = object; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("take my phone"); Object result = method.invoke(object,args); System.out.println("smell bad"); return result; } } public class TestProxy { public static void main(String[] args) { Subject subject = new RealSubject(); ProxyHandler proxyHandler = new ProxyHandler(subject); Subject subjectProxy = (Subject)Proxy.newProxyInstance(subject.getClass().getClassLoader(), subject.getClass().getInterfaces(),proxyHandler); subjectProxy.toilet(); } }
动态代理(cglib):
public class CglibProxyInterceptor implements MethodInterceptor{ public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { System.out.println("take my phone"); Object o1 = methodProxy.invokeSuper(o, args); System.out.println("smell bad"); return o1; } } public class CglibProxyTest { public static void main(String[] args) { CglibProxyInterceptor cglibProxyInterceptor = new CglibProxyInterceptor(); Enhancer enhancer = new Enhancer(); enhancer.setCallback(cglibProxyInterceptor); enhancer.setSuperclass(RealSubject.class); Subject subject = (Subject)enhancer.create(); subject.toilet(); } }