Java是一門非常流行的編程語(yǔ)言,其擁有許多高級(jí)特性,其中靜態(tài)代理和動(dòng)態(tài)代理是其中非常重要的特性之一。
Java中的靜態(tài)代理,是指在編譯時(shí)就已經(jīng)確定需要代理的對(duì)象,由程序員手動(dòng)編寫代理方法的代碼。這種代理需要在每個(gè)代理對(duì)象中都重寫一遍代理方法,代碼重復(fù)率相對(duì)較高。
public interface Subject { void doSomething(); } public class StaticProxy implements Subject { private Subject subject; public StaticProxy(Subject subject) { this.subject = subject; } @Override public void doSomething() { System.out.println("Before do something"); subject.doSomething(); System.out.println("After do something"); } } public class Client { public static void main(String[] args) { Subject subject = new RealSubject(); StaticProxy proxy = new StaticProxy(subject); proxy.doSomething(); } }
動(dòng)態(tài)代理則是在運(yùn)行時(shí)動(dòng)態(tài)生成代理對(duì)象,無(wú)需手動(dòng)編寫重復(fù)的代碼。它利用反射機(jī)制和代理設(shè)計(jì)模式實(shí)現(xiàn)了代理的效果,可以節(jié)省很多開(kāi)發(fā)時(shí)間和代碼量。
public interface DynamicSubject { void doSomething(); } public class RealDynamicSubject implements DynamicSubject { @Override public void doSomething() { System.out.println("Real do something"); } } public class DynamicProxy implements InvocationHandler { private Object realObject; public DynamicProxy(Object realObject) { this.realObject = realObject; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before do something"); Object result = method.invoke(realObject, args); System.out.println("After do something"); return result; } } public class Client { public static void main(String[] args) { DynamicSubject subject = new RealDynamicSubject(); DynamicSubject proxy = (DynamicSubject) Proxy.newProxyInstance( subject.getClass().getClassLoader(), subject.getClass().getInterfaces(), new DynamicProxy(subject) ); proxy.doSomething(); } }
靜態(tài)代理適用于只有少量接口需要代理的情況,而且代理類與委托類的接口類型必須一致,不靈活。而動(dòng)態(tài)代理適用于代理類與委托類的接口類型不一致或者需要代理的接口過(guò)多的情況。