委托模式是軟件設計模式中的一項基本技巧。在委托模式中,有兩個對象參與處理同一個請求,接受請求的對象將請求委托給另一個對象來處理。委托模式是一項基本技巧,許多其他的模式,如狀態模式、策略模式、訪問者模式 本質上是在更特殊的場合采用了委托模式。委托模式使得我們可以用聚合來替代繼承,它還使我們可以模擬mixin。
“委托”在C#中是一個語言級特性,而在Java語言中沒有直接的對應,但是我們可以通過動態代理來實現委托!代碼如下:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public abstract class Delegator implements InvocationHandler {
//--------------------------------------------
protected Object obj_orgin = null; //原始對象
protected Object obj_proxy = null; //代理對象
//--------------------------------------------
public Delegator() {
}
public Delegator(Object orgin) {
this.createProxy(orgin);
}
protected Object createProxy(Object orgin) {
obj_orgin = orgin;
//下面語句中orgin.getClass().getClassLoader()為加載器,orgin.getClass().getInterfaces()為接口集
obj_proxy = Proxy.newProxyInstance(orgin.getClass().getClassLoader(), orgin.getClass().getInterfaces(), this); //委托
return obj_proxy;
}
protected Object invokeSuper(Method method, Object[] args) throws Throwable {
return method.invoke(obj_orgin, args);
}
//--------------實現InvocationHandler接口,要求覆蓋------------
//下面實現的方法是當委托的類調用toString()方法時,操作其他方法而不是該類默認的toString(),這個類的其他方法則不會。
public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
// 缺省實現:委托給obj_orgin完成對應的操作
if (method.getName().equals("toString")) { //對其做額外處理
return this.invokeSuper(method, args) + "$Proxy";
} else { //注意,調用原始對象的方法,而不是代理的(obj==obj_proxy)
return this.invokeSuper(method, args);
}
}
}
下面的代碼,則是作為一個委托的例子,實現Map的功能。
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.bs2.core.UtilLog;
public class Delegator4Map extends Delegator {
private static Log _log = LogFactory.getLog(Delegator4Map.class);
private Map orginClass = null; //原始對象
private Map proxyClass = null; //代理對象
public Map getOrgin() {
return orginClass;
}
public Map getProxy() {
return proxyClass;
}
public Delegator4Map(Map orgin) {
super(orgin);
orginClass = orgin;
proxyClass = (Map) super.obj_proxy;
}
public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
if (method.getName().equals("size")) { //修改size處理邏輯
Object res2 = new Integer(-1);
System.out.println("調用委托的方法");
return res2;
} else {
System.out.println("調用原始的方法");
return super.invoke(obj, method, args);
}
}
public static void main(String[] args) throws IOException {
Delegator4Map rtm = new Delegator4Map(new Hashtable());
Map m = rtm.getProxy();
m.size();
}
} 秀萌寶照片,酷贏“拉比盒子” 游戲測試:三國時期誰是你最好的兄弟!! 發現興趣所在,玩轉新浪Qing!