Posted on 2007-01-05 20:43
chenweicai 閱讀(192)
評論(0) 編輯 收藏
代理模式一般有三個角色:
1。抽象主題角色(interface or abstract class)
package ProxyPattern;
/**
?* 抽象主題角色,定義了公共接口
?* @author chenweicai
?*
?*/
public interface Merchant {
?public void treat();
}
2。真實主題角色
package ProxyPattern;
/**
?* 真實主題角色,實現了抽象主題接口
?*
?* @author?chenweicai
?*
?*/
public class Director implements Merchant {
?public Director() {
?}
?public void treat() {
??// TODO Auto-generated method stub
??System.out.println("董事長請大家吃飯!");
?}
}
3。代理主題角色
package ProxyPattern;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
?* 代理主題角色
?*
?* @author?chenweicai?
?*/
public class Secretory implements InvocationHandler {
?/**
? * 定義真實主題
? */
?private Director director;
?
?public Secretory(Director director) {
??this.director = director;
?}
?public Object invoke(Object proxy, Method method, Object[] args)
???throws Throwable {
??// TODO Auto-generated method stub
??director.treat();
??System.out.println("由秘書來結帳哦!");
??return null;
?}
}
//---------------------------------------------------
??Director director = new Director();
??InvocationHandler secretory = new Secretory(director);
??Merchant merchant = (Merchant) Proxy.newProxyInstance(director
????.getClass().getClassLoader(), director.getClass()
????.getInterfaces(), secretory);
??merchant.treat();