How does method chaining work?

风流意气都作罢 提交于 2019-12-17 21:23:44

问题


How does getRequestDispatcher("xxx") get called from getServletContext() in the example below? How does calling procedures like this work in general? Please give me a clear picture about this context.

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.include(request, response);

回答1:


getServletContext() returns a ServletContext object, which has a method called getRequestDispatcher(). Your line of code is just shorthand for two method calls, and is equivalent to this code:

ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/index.jsp");



回答2:


in general, method chaining is a good practice achieving fluent and flexible interfaces. Generally... to achieve it, you just do your code and return the current object. For example, in Java:

public Criterios<T> setOrdem(String campo, String direcao) {
    getOrdenacao().set(campo, direcao);
    return this;
}

public Criterios<T> setOrdem(String campo) {
    return setOrdem(campo, Ordenacao.Direcao.ASC);
}

public final Criterios<T> setPagina(int pagina) {
    getPaginacao().setPagina(pagina);
    return this;
}

public final Criterios<T> setQuantidade(int quantidade) {
    getPaginacao().setQuantidade(quantidade);
    return this;
}

Returning the current object provides the same API over and over... but, by each iteration the object gets changed, step by step, orderly.



来源:https://stackoverflow.com/questions/28367123/how-does-method-chaining-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!