如何在java中实现方法链接?我想在Java中实现方法链接。我怎样才能实现它?也让我知道何时使用它。public class Dialog {
public Dialog() {
}
public void setTitle(String title) {
//Logic to set title in dialog
}
public void setMessage(String message) {
//Logic to set message
}
public void setPositiveButton() {
//Logic to send button
}}我想创建方法链,我可以使用如下:new Dialog().setTitle("Title1").setMessage("sample message").setPositiveButton();或者喜欢new Dialog().setTitle("Title1").setMessage("sample message");或者喜欢new Dialog().setTitle("Title1").setPositiveButton();
3 回答
慕无忌1623718
TA贡献1744条经验 获得超4个赞
只需添加一个静态构建器方法,然后创建另一组setter方法。例如
class Model { private Object FieldA; private Object FieldB; public static Model create() { return new Model(); } public Model withFieldA(Object value) { setFieldA(value); return this; } public Model withFieldB(Object value) { setFieldB(value); return this; }}
...
并使用它
Model m = Model.create().withFieldA("AAAA").withFieldB(1234);
添加回答
举报
0/150
提交
取消