ThinkJDBC源码解析(一) 链式函数与D.M()方法实现

《ThinkJDBC—一行代码搞定数据库操作》 项目地址 https://gitee.com/Leytton/ThinkJD

0x01 链式调用

首先我们来实现链式调用方法,所谓链式调用就是一行代码能多次调用对象方法,类似语法格式为
new M().table("user").field("id,name").where("id=3").find();

ThinkJD的主要数据库逻辑是在M类里实现的,首先建立M.java类,并添加构造方法M()M(String table),和两个普通方法field()where()分别用于给field、where属性赋值。

public class M {

    private String table;
    private String field;
    private String where;

    public M(){
    }
    public M(String table){
        this.table=table;
    }
    public void field(String filed) {
        this.field = filed;
    }
    public void where(String where) {
        this.where = "where " + where;
    }
}

此时M m=new M("user");返回的是一个table属性值为user的对象实例m。给field属性赋值,m.field("id,name");,再给where属性赋值m.where("id=3");此处用了3行代码才完成。
那么改成下面代码

public class M {
    ...
    public M field(String filed) {
        this.field = filed;
        return this;
    }
    public M where(String where) {
        this.where = "where " + where;
        return this;
    }
}

与上面代码不同的是field()where()方法都添加了返回语句return this;返回的是M实例对象本身。new M("user") 返回的是实例对象假设为mm调用field()方法:new M("user").field("id,name") 返回的还是对象m!!! m再调用where()方法:new M("user").field("id,name").where("id=3") 返回的依旧是对象m!!!这样就可以多次连续甚至重复调用m里的方法了。
在此,我们实现了M类里的链式调用方法。

链式调用方法还经常用于javaBean对象。如new User().setId(123).setName(“Leytton”)

0x02 D.M()方法实现

每次创建M类对象都要 new M(),ThinkJD提供了更快的调用方式D.M()
查看源码

public class D {
    ...
    public static M M() throws SQLException {
        return new M();
    }
    public static M M(String table) throws SQLException {
        return new M(table);
    }
}

D类的M()和M(String table)是静态方法,不需要new出一个实例对象就可以调用D.M(),返回的是M类实例对象。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值