Posted on 2007-01-05 20:43
chenweicai 阅读(186)
评论(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();