流接口模式

模式定义

在软件工程中,流接口(Fluent Interface)是指实现一种面向对象的,能提高代码可读性的API的方法,其目的就是可以编写具有自然语言一样可读性的代码,我们对这种代码编写方式还有一个通俗的称呼 -- 方法链

UML类图

示例代码

public class Sql {

    private String[] fields;

    private String[] from;

    private String[] where;

    public Sql select(String... fields) {
        this.fields = fields;

        return this;
    }

    public Sql from(String... from) {
        this.from = from;

        return this;
    }

    public Sql where(String... where) {
        this.where = where;

        return this;
    }

    public String getQuery() {

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("SELECT ")
                .append(String.join(", ", fields))
                .append(" FROM ")
                .append(String.join("", from))
                .append(" WHERE ")
                .append(String.join(" AND ", where));
        return sqlBuilder.toString();
    }

    public static void main(String[] args) {
        Sql sql = new Sql();
        sql.select("a", "b", "c").from("table AS a").where("a=1", "b=1");
        String query = sql.getQuery();
        System.out.println(query);
    }
}

results matching ""

    No results matching ""