How does method chaining work?

北城以北 提交于 2019-11-28 14:50:06
AGreenman

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");

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.

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