代理模式
代理模式 實現(xiàn)邏輯和實現(xiàn)的解耦
代理模式 為了提供額外的的操作,插入用來代替實際對象的對象。這些操作通常涉及與實際對象通信,代理充當中間人的角色
- 接口
/**
* 接口
*/
public interface Interface {
void doSomething();
void somethingElse(String arg);
}
- 實際對象
/**
* 實際對象
*/
public class RealObject implements Interface {
public void doSomething() {
System.out.println("doSomething");
}
public void somethingElse(String arg) {
System.out.println("somethingElse" + arg);
}
}
- 代理對象
/**
* 代理對象
*/
public class Proxy implements Interface {
private Interface proxied;
public Proxy(Interface proxied) {
this.proxied = proxied;
}
public void doSomething() {
System.out.println("Proxy doSomething");
proxied.doSomething();
}
public void somethingElse(String arg) {
System.out.println("Proxy somethingElse" + arg);
proxied.somethingElse(arg);
}
}
- 測試
/**
* 測試代理,比較原對象與代理對象
*
* @param args
*/
public static void main(String[] args) {
Interface iface = new RealObject();
iface.doSomething();
iface.somethingElse("bonobo");
Interface iface2 = new Proxy(iface);
iface2.doSomething();
iface2.somethingElse("bonobo");
}
動態(tài)代理
Java動態(tài)代理可以動態(tài)創(chuàng)建代理并動態(tài)處理對所代理的方法的調(diào)用
在動態(tài)里上所做的所有調(diào)用都會被重定向到單一的調(diào)用處理器上,它的工作是揭示調(diào)用的類型并確定對應的對策
- 動態(tài)代理
public class DynamicProxyHandler implements InvocationHandler {
private Object proxied;
public DynamicProxyHandler(Object proxied) {
this.proxied = proxied;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("**** proxy:" + proxy.getClass() + ".method: " + method + ".args: " + args);
if (args != null) {
for (Object arg : args) {
System.out.println(" " + args);
}
}
return method.invoke(proxied, args);
}
}
- 測試
public static void main(String[] args){
RealObject real = new RealObject();
real.doSomething();
real.somethingElse("bonobo");
Interface proxy = (Interface) Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[]{Interface.class},
new DynamicProxyHandler(real));
proxy.doSomething();
proxy.somethingElse("bonobo");
}