Java中的鏈式調(diào)用

MsgInfo msgInfo = new MsgInfo();
        msgInfo.setOwnerId("100011002")
                .setRelatedId("1000110003")
                .setBody("hello 鏈式調(diào)用")
                .setType(MsgInfo.Type.TEXT)
                .setDirect(MsgInfo.Direct.SEND)
                .setStatus(MsgInfo.Status.SENDING)
                .setTime(System.currentTimeMillis());
    有時開發(fā)中我們會看到這種這種寫法,這是如何實現(xiàn)的呢,代碼如下:
    public class Persion {
    private int id;
    private String name;
    private String phoneNumber;
    private String address;
    public  Persion() {
    }
    public Persion setId(int id) { 
        this.id = id;
        return this;
    }
    public Persion setName(String name) {
        this.name = name;
        return this;
    }
    public Persion setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
        return this;
    }
    public Persion setAddress(String address) {
        this.address = address;
        return this;
    }
    public Persion printId() {
        System.out.println(this.id);
        return this;
    }
    public Persion printName() {
        System.out.println(this.name);
        return this;
    }
    public Persion printPhoneNumber() {
        System.out.println(this.phoneNumber);
        return this;
    }
    public Persion printAddress() {
        System.out.println(this.address);
        return this;
    }
}

JavaScript中可以這樣寫

function Dog(){
    this.run= function(){
      alert("The dog is running....");
      return this;//返回當(dāng)前對象 Dog
    };
    this.eat= function(){
      alert("After running the dog is eatting....");
      return this;//返回當(dāng)前對象 Dog
 
    };
    this.sleep= function(){
      alert("After eatting the dog is running....");
      return this;//返回當(dāng)前對象 Dog
 
    };
  }

本質(zhì)上是在set值得時候返回this
這種寫法經(jīng)常與Builder設(shè)計模式一起使用,在Android中有大量實現(xiàn)。當(dāng)然在用這種方式不利于代碼調(diào)試。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容