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)試。