委派模式

1.什么是委派模式

委派模式不属于23种设计模式中,但是是在spring中用的比较多的一种模式,比如Spring MVC中的DispatcherServlet就用到了委派模式,委派模式主要负责任务的调度以及分配任务,它和代理模式很像,可以看作是特殊情况下的静态代理的全权代理,但是代理模式注重过程,委派模式注重结果。

2.举例说明

下图主要说明了 boss把任务给leader,而leader做了一个任务的分配和调度的工作,自己没有做工作,而是把具体工作交给具体的执行者去做。

 

 

3.代码实现

 

下面直接给出实例:

执行的接口

/**
 * @Project: spring
 * @description: 执行的接口
 * @author: sunkang
 * @create: 2018-08-30 23:10
 * @ModificationHistory who      when       What
 **/
public interface IExcuter {
    void excute(String command);
}

普通员工A

/**
 * @Project: spring
 * @description: 员工A执行某项命令
 * @author: sunkang
 * @create: 2018-08-30 23:10
 * @ModificationHistory who      when       What
 **/
public class ExcuterA implements  IExcuter{

    @Override
    public void excute(String command) {
        System.out.println("员工A 开始做"+command+"的工作");
    }
}

普通员工B

/**
 * @Project: spring
 * @description: 员工B执行某项命令
 * @author: sunkang
 * @create: 2018-08-30 23:10
 * @ModificationHistory who      when       What
 **/
public class ExcuterB implements  IExcuter{
    @Override
    public void excute(String command) {
        System.out.println("员工B 开始做"+command+"的工作");
}
}

leader委派者

/**
 * @Project: spring
 * @description:    leader 委派者   任务分发的作用
 * @author: sunkang
 * @create: 2018-08-30 23:11
 * @ModificationHistory who      when       What
 **/
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类模拟调用测试

/**
 * @Project: spring
 * @description:  boss  模拟客户执行任务
 * @author: sunkang
 * @create: 2018-08-30 23:13
 * @ModificationHistory who      when       What
 **/
public class Boss
{
    public static void main(String[] args) {
        Leader leader  = new Leader();
        //看上去好像是我们的项目经理在干活
        //但实际干活的人是普通员工
        //这就是典型,干活是我的,功劳是你的
        leader.excute("登录");
        leader.excute("加密");
    }
}


作者:Mrsunup
链接:https://www.jianshu.com/p/38acf37b1e1f
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

posted @ 2021-01-25 11:18  Yaoyaoo  阅读(221)  评论(0)    收藏  举报