委派模式

委派模式的定义及应用场景

  委派模式(Delegate Pattern)不属于GoF 23 种设计模式。委派吗,模式的基本作用就是负责任务的调用和分配,根代理模式很像,可以看作一种特殊情况下的静态的全权代理,但是代理模式注重过程,而委派模式注重结果。委派模式在 Spring 中应用的非常多,常用的DispacherServlet 就用到了委派模式。现实生活中也常有委派的场景发生,例如老板(Boss)给项目经理(Leader)下达任务,项目经理会根据实际情况给每个员工派发任务,待员工把任务完成后,再由项目经理向老板汇报结果。

  创建 IEployee 员工接口: 

package com.xq.design.delegate.simple;

public interface IEployee {
    public void doing(String command);
}

  创建员工类  EmployeeA :

package com.xq.design.delegate.simple;

public class EmployeeA implements IEployee {
    @Override
    public void doing(String command) {
        System.out.println("我是员工A,我现在开始干"+ command + "工作");
    }
}

  创建员工类  EmployeeB :

package com.xq.design.delegate.simple;

public class EmployeeB implements IEployee {
    @Override
    public void doing(String command) {
        System.out.println("我是员工B,我现在开始干" + command + "工作");
    }
}

  创建项目经理类 Leader :

package com.xq.design.delegate.simple;

import java.util.HashMap;
import java.util.Map;

public class Leader implements IEployee {
    private Map<String,IEployee> targets = new HashMap<String, IEployee>();
    //项目经理自己不干活
    public void doing(String command) {
        targets.get(command).doing(command);
    }
    public Leader(){
        targets.put("加密", new EmployeeA());
        targets.put("登录",new EmployeeB());
    }
}

  创建 Boss 类下达命令:

package com.xq.design.delegate.simple;

public class Boss {
    public void command(String command, Leader leader){
        leader.doing(command);
    }
}

  测试代码如下:

package com.xq.design.delegate.simple;

public class DelegateTest {
    public static void main(String[] args) {
        //代理模式注重过程,委派模式注重的是结果
        //策略模式注重可扩展性(外部扩展性),委派模式注重内部灵活性和可复用性
        //委派模式的核心就是分发、调度、派遣,委派模式是静态代理和策略模式的一种特殊组合
        new Boss().command("登录",new Leader());
    }
}

本文来自博客园,作者:l-coil,转载请注明原文链接:https://www.cnblogs.com/l-coil/p/12871483.html

原文地址:https://www.cnblogs.com/xianquan/p/12871483.html