一.委派模式的定义及应用场景
委派模式不属于GOF23种设计模式中,它的基本作用就是负责任务的调用和分配任务,Spring中的DispatcherServlet就是用到了委派模式,现实生活中也常有委 派的场景发生,例如:老板(Boss)给项目经理(Leader)下达任务,项目经理会根据 实际情况给每个员工派发工作任务,待员工把工作任务完成之后,再由项目经理汇报工 作进度和结果给老板。
二.代码实现
1.先创建一个员工接口
public interface IEmployee {
public void doing(String command);
}
2.创建员工A和员工B
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+"工作");
}
}
3.创建一个项目经理
public class Leader implements IEmployee {
private Map<String,IEmployee> targets=new HashMap<>();
public Leader() {
targets.put("加密",new EmployeeA());
targets.put("登录",new EmployeeB());
}
//经理自己不干活
@Override
public void doing(String command) {
IEmployee iEmployee = targets.get(command);
if(iEmployee!=null){
iEmployee.doing(command);
}else {
System.out.println("还没有能干这个活的员工");
}
}
}
4.创建Boss类下达命令
public class Boss {
public void command(String command,Leader leader){
leader.doing(command);
}
}
5.测试类
public class DelegateTest {
public static void main(String[] args) {
Boss boss = new Boss();
// boss.command("加密",new Leader());
// boss.command("登录",new Leader());
// boss.command("注册",new Leader());
}
}
6.总结
客户请求(Boss),委派者(Leader),被委派者(Target),委派者要持有被委派者的引用
二.委派模式在源码中的体现
SpringMVC中的DispatcherServlet就相当于项目经理的角色