委託代理模式

委託模式是軟體設計模式中的一項基本技巧。在委託模式中,有兩個對象參與處理同一個請求,接受請求的對象將請求委託給另一個對象來處理。

基本介紹

  • 中文名:委託代理模式
  • 實質:軟體設計模式中的一項基本技巧
  • 要求:有兩個對象參與處理同一個請求
  • 包括:狀態模式、策略模式
簡介,舉例,

簡介

委託模式是一項基本技巧,許多其他的模式,如狀態模式策略模式訪問者模式本質上是在更特殊的場合採用了委託模式。委託模式使得我們可以用聚合來替代繼承,它還使我們可以模擬mixin。
“委託”在C#中是一個語言級特性,而在Java語言中沒有直接的對應,但是我們可以通過動態代理來實現委託!代碼如下:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*
* @author Liusheng
* 實現“委託”模式,用戶需要實現InvocationHandler接口;
*/
public abstract class Delegator implements InvocationHandler {
//RelegateTo針對每個對象都要生成一個實例,因而非Static的log,代價比較高。
//protected Log _log = LogFactory.getLog(this.getClass());
//private static Log _log = LogFactory.getLog(RelegateTo.class);
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;
obj_proxy = Proxy.newProxyInstance(
orgin.getClass().getClassLoader(), //載入器
orgin.getClass().getInterfaces(), //接口集
this); //委託
//_log.debug("# 委託代理:"+obj_proxy);
return obj_proxy;
}
protected Object invokeSuper(Method method, Object[] args)
throws Throwable {
return method.invoke(obj_orgin, args);
}
//--------------實現InvocationHandler接口,要求覆蓋------------
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;
/**
* @author Liusheng
* 本代碼主要用於演示RelegateTo的使用方法
*/
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")) { //修改close處理邏輯
_log.debug("原始 size()="+super.invoke(obj, method, args));
Object res2 = new Integer(-1);
_log.debug("修改 size()="+res2);
return res2;
}else {
return super.invoke(obj, method, args);
}
}
public static void main(String[] args) throws IOException {
UtilLog.configureClassPath("resources/log4j.properties", false);
Delegator4Map rtm = new Delegator4Map(new Hashtable());
Map m = rtm.getProxy();
m.size();
_log.debug("代理:"+m.toString());
}
}

相關詞條

熱門詞條

聯絡我們