如何在java中实现方法链?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21180269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:08:52  来源:igfitidea点击:

how to achieve method chaining in java?

javamethodschaining

提问by Bug

I want to achieve method chaining in Java.

我想在 Java 中实现方法链。

How can I achieve it?

我怎样才能实现它?

Also let me know when to use it.

也让我知道什么时候使用它。

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
     }
}   

I want to create method chaining that I can use as follows:

我想创建方法链,我可以使用如下:

new Dialog().setTitle("Title1").setMessage("sample message").setPositiveButton();

or like

或喜欢

new Dialog().setTitle("Title1").setMessage("sample message");

or like

或喜欢

new Dialog().setTitle("Title1").setPositiveButton();

采纳答案by lucian.pantelimon

Have your methods return thislike:

让您的方法返回this如下:

public Dialog setMessage(String message)
{
    //logic to set message
    return this;
}

This way, after each call to one of the methods, you'll get the same object returned so that you can call another method on.

这样,在每次调用其中一个方法后,您将得到相同的对象返回,以便您可以调用另一个方法。

This technique is useful when you want to call a series of methods on an object: it reduces the amount of code required to achieve that and allows you to have a single returned value after the chain of methods.

当您想在一个对象上调用一系列方法时,此技术很有用:它减少了实现这一目标所需的代码量,并允许您在方法链之后有一个返回值。

An example of reducing the amount of code required to show a dialog would be:

减少显示对话框所需的代码量的示例是:

// Your Dialog has a method show() 
// You could show a dialog like this:
new Dialog().setMessage("some message").setTitle("some title")).show();

An example of using the single returned value would be:

使用单个返回值的示例是:

// In another class, you have a method showDialog(Dialog)
// Thus you can do:
showDialog(new Dialog().setMessage("some message").setTitle("some title"));

An example of using the Builder pattern that Dennis mentioned in the comment on your question:

使用丹尼斯在对您的问题的评论中提到的 Builder 模式的示例:

new DialogBuilder().setMessage("some message").setTitle("some title").build().show();

The builder pattern allows you to set all parameters for a new instance of a class before the object is being built (consider classes that have finalfields or objects for which setting a value after it's been built is more costly than setting it when it's constructed).

构建器模式允许您在构建对象之前为类的新实例设置所有参数(考虑具有final字段或对象的类,在构建后为其设置值比在构建时设置它的成本更高)。

In the example above: setMessage(String), setTitle(String)belong to the DialogBuilderclass and return the same instance of DialogBuilderthat they're called upon; the build()method belongs to the DialogBuilderclass, but returns a Dialogobject the show()method belongs to the Dialogclass.

在上面的例子中:setMessage(String)setTitle(String)属于DialogBuilder该类并返回DialogBuilder它们被调用的相同实例;该build()方法属于DialogBuilder该类,但返回Dialogshow()方法属于Dialog该类的对象。

Extra

额外的

This might not be related to your question, but it might help you and others that come across this question.

这可能与您的问题无关,但它可能会帮助您和遇到此问题的其他人。

This works well for most use cases: all use cases that don't involve inheritance and some particular cases involving inheritance when the derived class doesn't add new methods that you want to chain together andyou're not interested in using (without casting) the result of the chain of methods as an object of the derived.

这适用于大多数用例:所有不涉及继承的用例和一些涉及继承的特定情况,当派生类没有添加您想要链接在一起的新方法并且您不感兴趣使用(不进行强制转换) ) 方法链的结果作为派生对象。

If you want to have method chaining for objects of derived classes that don't have a method in their base class or you want the chain of methods to return the object as a reference of the derived class, you can have a look at the answers for this question.

如果您想为基类中没有方法的派生类的对象使用方法链,或者您希望方法链将对象作为派生类的引用返回,您可以查看答案对于这个问题

回答by Chandru Sekar

example of reducing the amount of code required to show a dialog would be:

减少显示对话框所需的代码量的示例是:

package com.rsa.arraytesting;

public class ExampleJavaArray {

String age;
String name;

public ExampleJavaArray getAge() {
    this.age = "25";
    return this;
}

public ExampleJavaArray setName(String name) {
    this.name = name;
    return this;
}
public void displayValue() {
    System.out.println("Name:" + name + "\n\n" + "Age:" + age);
}
}

another class

另一个班级

package com.rsa.arraytesting;

public class MethodChaining {

public static void main(String[] args) {

    ExampleJavaArray mExampleJavaArray = new ExampleJavaArray();

    mExampleJavaArray.setName("chandru").getAge().displayValue();

}

}

回答by Vagif

Just add a static builder method, and create another set of the setter methods. For example

只需添加一个静态构建器方法,并创建另一组 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;
   }
}

...

...

And use it like

并使用它

 Model m = Model.create().withFieldA("AAAA").withFieldB(1234);