内容都是从Tom老师的书中摘抄,记录下来方便自己学习。
委派模式的基本作用就是负责任务的调用和分配,跟代理模式很像,可以看作一种特殊情况下的静态的全权代理,但是代理模式注重过程,而委派模式注重结果。DispatcherServlet就用到了委派模式。
public interface IEmployee {
void doing(String command);
}
public class EmployeeA implements IEmployee {
@Override
public void doing(String command) {
System.out.println("我是员工A,我现在开始干"+command+"工作");
}
}
public class EmployeeB implements IEmployee {
@Override
public void doing(String command) {
System.out.println("我是员工B,我现在开始干"+command+"工作");
}
}
public class Leader implements IEmployee {
private Map<String ,IEmployee> targets=new HashMap<>();
public Leader(){
targets.put("jiami",new EmployeeA());
targets.put("denglu",new EmployeeB());
}
@Override
public void doing(String command) {
targets.get(command).doing(command);
}
}
public class Boss {
public void command(String command,Leader leader){
leader.doing(command);
}
}
public class Test {
public static void main(String[] args) {
//代理模式注重过程,委派模式注重结果
//策略模式注重可扩展性(外部可扩展性),委派模式注重内部的灵活性和可复用性
//委派模式的核心就是分发、调度、派遣,委派模式是静态代理和策略模式的一种特殊组合
new Boss().command("jiami",new Leader());
}
}