1.委派模式简介
在常用的23种设计模式中其实面没有委派模式(delegate),但是在Spring中委派模式确实用的比较多的一种模式。
Spring MVC框架中的DispatcherServlet其实就用到了委派模式。
委派模式的作用: 基本作用就是负责任务的调用和分配任务,跟代理模式很像,可以看做是一种特殊情况下的静态代理的全权代理,但是代理模式注重过程,而委派模式注重结果。
类图:
实例:
Boos类:(相当于客户端)
public class Boos {
private Leader leader;
public Boos(Leader leader){
this.leader = leader;
}
public void senCommand(String command){
leader.receiveCommand(command);
}
}
|
leader类:(委派类,要首先知道他可以委派的类)
public class Leader {
Map<String,IEmployee> EMPLOYEE_MAP = new HashMap<>();
public Leader(){
EMPLOYEE_MAP.put("设计图纸",new EmploveeA());
EMPLOYEE_MAP.put("码代码",new EmployeeB());
}
public void receiveCommand(String command){
if (EMPLOYEE_MAP.containsKey(command)){
EMPLOYEE_MAP.get(command).work(command);
}
}
}
|
员工接口:
public interface IEmployee {
void work(String command);
}
|
员工A:
public class EmploveeA implements IEmployee {
@Override
public void work(String command) {
System.out.println("员工A正在" + command);
}
}
|
员工B:
@Override
public void work(String command) {
System.out.println("员工B正在" + command);
}
|
测试类:
public class DelegateTest {
public static void main(String[] args) {
Boos boos = new Boos(new Leader());
boos.senCommand("设计图纸");
}
}
|
总结:
委派模式,其实就是你要做的事情,你(BOOS)委派个一个人(Leader),让他分发下去,让别人(EmployeeA、EmployeeB)做,做完之后把结果返回来给那个人(Leader),然后他在把结果返回给你(Boos)就可以了。