导读
在spring中委派模式用的比较多,在常用的23种设计模式中其实是没有委派模式的影子的。
在spring中体现:Spring MVC框架中的DispatcherServlet其实就用到了委派模式。
委派模式的作用:基本作用就是负责任务的调用和分配,跟代理模式很像,可以看做是一种特殊情况下的静态代理的全权代理,但是代理模式注重过程,而委派模式注重结果。
Example
利用一张图简述委派模式,下图简单说明了老板把任务给了项目经理,而项目经理将任务拆分,分给一个个it攻城狮,自己没有做工作,而是把具体工作交给具体的执行者去做。

代码示例
接口:IExcuter.java
public interface IExcuter {
void excute(String command);
}
攻城狮A:ExcuterA.java
public class ExcuterA implements IExcuter{
@Override
public void excute(String command) {
System.out.println("员工A 开始做"+command+"的工作");
}
}
攻城狮B:ExcuterB.java
public class ExcuterB implements IExcuter{
@Override
public void excute(String command) {
System.out.println("员工B 开始做"+command+"的工作");
}
}
项目经理(委派者):Leader.java
public class Leader implements IExcuter {
private Map<String,IExcuter> targets = new HashMap<String,IExcuter>();
public Leader() {
targets.put("加密",new ExcuterA());
targets.put("登录",new ExcuterB());
}
@Override
public void excute(String command) {
targets.get(command).excute(command);
}
}
老板:Boss.java
public class Boss
{
public static void main(String[] args) {
Leader leader = new Leader();
//看上去好像是我们的项目经理在干活
//但实际干活的人是普通员工
//这就是典型,干活是我的,功劳是你的
leader.excute("登录");
leader.excute("加密");
}
}
实现

参考:https://www.jianshu.com/p/38acf37b1e1f