委派模式详解

       委派模式的基本作用就是负责任务的调用和分配,类似于代理模式,但是代理模式注重过程,而委派模式注重结果。委派模式在spring中应用的非常的多,现实生活中场景也是非常的多。比如程序员,当老板给项目经理下达任务后,项目经理再把任务分派给相应的员工。

创建员工接口

public interface IEmployee {
    public void doing(String commond);
}

创建员工类,员工A

public class IEmployeeA  implements  IEmployee{

    @Override
    public void doing(String commond) {
        System.out.println("aaaaaaaaaaaaaaaa");
    }
}

创建员工类,员工B

public class IEmployeeB implements IEmployee {
    @Override
    public void doing(String commond) {
        System.out.println("bbbbbbbbbbbbbbbbbb");
    }
}

创建项目经理类

public class Leader implements IEmployee {

    private Map<String ,IEmployee> targets = new HashMap<String,IEmployee>();
    public Leader(){
        targets.put("前端",new IEmployeeA());
        targets.put("后端",new IEmployeeB());
    }
    @Override
    public void doing(String commond) {
        targets.get(commond).doing(commond);

    }
}

创建Boss类

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

创建测试类

public class DemoUtil {
    public static void main(String[] args) throws Exception{
      
        new Boss().command("后端",new Leader());
    }
}

测试结果:

bbbbbbbbbbbbbbbbbb

从上述结果可以看到,因为项目经理把任务安排给了后端的员工,因此是员工B,做的Boss安排的这个工作。

spring中DispatcherServlet就是使用的委派模式,以Delegate结尾的地方都实现了委派模式。

那么spring MVC中dispatcherServlet是怎么实现委派模式的呢?

创建业务类

public class ItemController {
    public void getItemById(){};
}
public class OrderController {
    public void getOrderById(){};
}

创建DispatcherServlet类

public class DispatcherServlet extends HttpServlet {
    private void doDispatch(HttpServletRequest request,HttpServletResponse response){
        String uri = request.getRequestURI();
        String id = request.getParameter("mid");

        if("getItemById").equals(uri){
            new ItemController().getItemById(id);
        }else if("getOrderById".equals(uri)){
            new OrderController().getOrderById(id);
        }else{
            response.getWriter().write("404 not found");
        }
    }

    protected void service(HttpServletRequest req,HttpServletResponse resp){
        try{
            doDispatch(req, resp);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

委派模式就到这里了,洗洗睡吧。

猜你喜欢

转载自blog.csdn.net/wzs535131/article/details/108589937