MsgInfo msgInfo = new MsgInfo();
msgInfo.setOwnerId("100011002")
.setRelatedId("1000110003")
.setBody("hello 链式调用")
.setType(MsgInfo.Type.TEXT)
.setDirect(MsgInfo.Direct.SEND)
.setStatus(MsgInfo.Status.SENDING)
.setTime(System.currentTimeMillis());
有时开发中我们会看到这种这种写法,这是如何实现的呢,代码如下:
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;//返回当前对象 Dog
};
this.eat= function(){
alert("After running the dog is eatting....");
return this;//返回当前对象 Dog
};
this.sleep= function(){
alert("After eatting the dog is running....");
return this;//返回当前对象 Dog
};
}
本质上是在set值得时候返回this
这种写法经常与Builder设计模式一起使用,在Android中有大量实现。当然在用这种方式不利于代码调试。